Redis:Spring Boot使用@Cacheable时设置部分缓存的过期时间

@Override
@Cacheable(cacheNames = {"distributor"}, key = "key1")
public List findCities() {
    return distributorMapper.selectCities();

@Override
@Cacheable(cacheNames = {"car"}, key = "key2")
public List findCities() {
    return distributorMapper.selectCities();

自定义缓存时间

distributor::key1 的有效期是永久的

car::key2 的有效期是6分钟

 

@Slf4j
@Configuration
@EnableCaching //启用缓存
public class RedisConfig {
	
	/**
	 * 自定义缓存管理器
	 */
	@Bean
	public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

		Set cacheNames = new HashSet<>();
		cacheNames.add("car");
		cacheNames.add("distributor");

		ConcurrentHashMap configMap = new ConcurrentHashMap<>();
		configMap.put("car", config.entryTtl(Duration.ofMinutes(6L)));//有效期6分钟
		configMap.put("distributor", config);//永久
		
		//需要先初始化缓存名称,再初始化其它的配置。
		RedisCacheManager cacheManager = RedisCacheManager.builder(factory).initialCacheNames(cacheNames).withInitialCacheConfigurations(configMap).build();

		return cacheManager;
	}
}

 

你可能感兴趣的:(Redis,redis,缓存)