一、引入依赖
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.8.8</version>
</dependency>
二、SpringBoot中service接口实现类使用
package com.aspire.hdc.product.service.serviceproduct.impl;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.aspire.hdc.product.api.service.serviceproduct.entity.*;
import com.aspire.hdc.product.api.service.serviceproduct.service.IProductCharge;
import com.aspire.hdc.product.api.service.serviceproduct.service.IServiceProduct;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Service
public class ServiceProductImpl implements IServiceProduct {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceProductImpl.class);
private static final String PRODUCT_CODE_KEY = "PRODUCT_CODE_KEY";
@Autowired
private ServicesProductDao servicesProductDao;
private LoadingCache<String, Map<String, ServiceProduct>> productInfoCache = null;
// 应用启动时,初始化,300s后自动刷新
@PostConstruct
public void initCache() {
productInfoCache = Caffeine.newBuilder().refreshAfterWrite(300, TimeUnit.SECONDS)
.build(k -> loadAllProducts());
productInfoCache.get(PRODUCT_CODE_KEY);
}
// 查询数据库,初始化到本地缓存(key->Object)
private Map<String, ServiceProduct> loadAllProducts() {
List<ServiceProduct> list;
Map<String, ServiceProduct> map = new HashMap<>();
try {
list = servicesProductDao.queryAllServiceProductInfos();
} catch (Exception e) {
LOGGER.error("初始化所有业务产品到本地缓存失败", e);
return map;
}
// 删除没有处理
if (list != null) {
for (ServiceProduct p : list) {
map.put(p.getProductCode(), p);
}
}
return map;
}
// 接口方法查询
@Override
public List<ServiceProduct> getAuthProductInfoListByCodes(String productCodes) {
List<ServiceProduct> productLists = Lists.newArrayList();
List<String> products = Arrays.asList(productCodes.split(","));
Map<String, ServiceProduct> prodMap = productInfoCache.get(PRODUCT_CODE_KEY);
for (String code : products) {
ServiceProduct serviceProduct = prodMap.get(code.replace("'", ""));
if (serviceProduct != null) {
productLists.add(serviceProduct);
} else {
LOGGER.debug("getAuthProductInfoListByCodes的产品编码不存在{}", code);
}
}
return productLists;
}
}