我通过自定义 cacheResolver 解决了这个问题,但似乎效率低下。
public class MyCacheResolver extends SimpleCacheResolver {
@Autowired
private RedisTemplate<Object, Object> template;
public CustomCacheResolver(CacheManager cacheManager) {
super(cacheManager);
}
@Override
public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
if (context.getOperation() instanceof CacheableOperation) {
DefaultParameterNameDiscoverer discover = new DefaultParameterNameDiscoverer();
CacheableOperation op = (CacheableOperation) context.getOperation();
String[] ps = discover.getParameterNames(context.getMethod());
EvaluationContext ctx = new StandardEvaluationContext();
for (int i = 0; i < ps.length; i++) {
ctx.setVariable(ps[i], context.getArgs()[i]);
}
ExpressionParser parser = new SpelExpressionParser();
String redisKey = parser.parseExpression(op.getKey()).getValue(ctx, String.class);
String prefix = getCacheNames(context).iterator().next();
long time = template.getExpire(prefix + ":" + redisKey);
if (time > 0) {
template.expire(prefix + ":" + redisKey, 300L, TimeUnit.SECONDS);
}
}
return super.resolveCaches(context);
}
}
就我而言,每次缓存命中都会自动将缓存 ttl 刷新到 300 秒。然后将 cacheResolver 注入配置类,
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean("customCacheResolver")
@Override
public CacheResolver cacheResolver() {
return new CustomCacheResolver(cacheManager());
}
@Bean
public RedisCacheManager cacheManager() {
//define your cacheManager here
}
}
我希望很清楚,英语不是我的母语。