findCities() { return distributor_@cacheabl">
赞
踩
业务场景: Spring Boot
项目中有一些查询数据需要缓存到Redis
中,其中有一些缓存是固定数据不会改变,那么就没必要设置过期时间。还有一些缓存需要每隔几分钟就更新一次,这时就需要设置过期时间。
Service
层部分代码如下:
@Override
@Cacheable(cacheNames = {"distributor"}, key = "#root.methodName")
public List<CityVO> findCities() {
return distributorMapper.selectCities();
}
@Override
@Cacheable(cacheNames = {"distributor"}, key = "#root.methodName.concat('#cityId').concat(#cityId)")
public List<DistributorVO> findDistributorsByCityId(String cityId) {
return distributorMapper.selectByCityId(cityId);
}
@Override
@Cacheable(cacheNames = {"car"}, key = "#root.methodName.concat('#cityId').concat(#cityId)")
public String carList(String cityId) {
RequestData data = new RequestData();
data.setCityId(cityId);
CarListParam param = new CarListParam();
param.setRequestData(data);
String jsonParam = JSON.toJSONString(param);
return HttpClientUtil.sendPostWithJson(ApiUrlConst.MULE_APP, jsonParam);
}
在使用@Cacheable
注解对查询数据进行缓存时,使用cacheNames
属性指定了缓存名称。下面我们就针对不同的cacheNames
来设置失效时间。
添加Redis
配置类RedisConfig.java
,代码如下:
@Slf4j @Configuration @EnableCaching //启用缓存 public class RedisConfig { /** * 自定义缓存管理器 */ @Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); Set<String> cacheNames = new HashSet<>(); cacheNames.add("car"); cacheNames.add("distributor"); ConcurrentHashMap<String, RedisCacheConfiguration> configMap = new ConcurrentHashMap<>(); configMap.put("car", config.entryTtl(Duration.ofMinutes(6L))); configMap.put("distributor", config); //需要先初始化缓存名称,再初始化其它的配置。 RedisCacheManager cacheManager = RedisCacheManager.builder(factory).initialCacheNames(cacheNames).withInitialCacheConfigurations(configMap).build(); return cacheManager; } }
以上代码,在configMap
中指定了cacheNames
为car
的缓存过期时间为6分钟
。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。