findCities() { return distributor_@cacheabl">
当前位置:   article > 正文

Spring Boot使用@Cacheable时设置部分缓存的过期时间_@cacheable 的缓存不更新是不是不会过期

@cacheable 的缓存不更新是不是不会过期

  业务场景: 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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
@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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

  在使用@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;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

以上代码,在configMap中指定了cacheNamescar的缓存过期时间为6分钟

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/353159
推荐阅读
相关标签
  

闽ICP备14008679号