一、先看问题代码
缓存管理器配置:
import java.util.concurrent.TimeUnit;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.benmanes.caffeine.cache.Caffeine;
@Configuration
public class CacheConfig {
private static final int EXPIRE_MINUTES = 5;
private static final int MAXIMUM_SIZE = 10000;
/**
* 配置缓存管理器
*
* @return 缓存管理器
*/
@Bean("cacheManager")
public CacheManager cacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(Caffeine.newBuilder()
// 设置最后一次写入或访问后经过固定时间过期
.expireAfterAccess(EXPIRE_MINUTES, TimeUnit.MINUTES)
// 初始的缓存空间大小
//.initialCapacity(100)
// 缓存的最大条数
.maximumSize(MAXIMUM_SIZE));
return cacheManager;
}
}
具体使用:
@Override
@Cacheable(value = "logicTypeCache", unless = "#result == null")
public Map<Long, String> getAllLogicType() {
log.info("TypeCacheService|getAllLogicType.");
try {
List<KeyValueResp> keyValueRespList = logicTypeApi.getAllLogicTypeName().getData();
if (CollectionUtils.isEmpty(keyValueRespList)) {
return new HashMap<>();
}
return keyValueRespList.stream().collect(Collectors.toMap(KeyValueResp::getId,
KeyValueResp::getName, (a, b) -> a));
} catch (Exception e) {
log.error("TypeCacheService|getAllLogicType error: {}", e.getMessage());
}
return new HashMap<>();
}
二、现象
一次上线后,发现缓存查出来的都是空,而且缓存一直不失效。查看线上调用日志,getAllLogicType()一直没有去请求更新缓存。查看之前的日志,发现基本也是一天才去更新一次缓存,有时候甚至不更新。
三、原因排查
这样看来应该是缓存策略配置的有问题,果然,问题出在数据过期策略上。具体原因有两个:
1、项目里用的expireAfterAccess,含义是最后一次访问之后,隔多久没有被再次访问的话,就过期。然而服务一直被访问,就一直不会过期。
2、@Cacheable的使用上也有问题。上线后,logicTypeApi请求超时,返回一个空的HashMap,不等于null,就被缓存了。加上其一的原因,就一直缓存着一个空的HashMap,就导致缓存查出来的一直是空。
四、修正后代码
1、缓存管理器配置:
修改缓存过期策略expireAfterAccess为expireAfterWrite,含义是某个数据在多久没有被更新后,就过期。
2、具体使用:
下游服务异常时应该不缓存。
修正后,线上缓存基本按照设定的时间更新: