有时候我们想自定义
@Cacheable的key,由于自定义的key通过方法的参数无法给出,这时候就需要使用keyGenerator了。
通过查看 @Cacheable 的源码可以看出我们自定义一个 KeyGenerator 需要实现一个接口KeyGenerator
/**
* The bean name of the custom {@link org.springframework.cache.interceptor.KeyGenerator}
* to use.
* <p>Mutually exclusive with the {@link #key} attribute.
* @see CacheConfig#keyGenerator
*/
String keyGenerator() default "";
首先定义一个 AdListCacheKeyGenerator来实现 KeyGenerator
/**
* @author 石冬冬(Chris Suk)
* @since 2022/10/20 4:36 PM
*/
@Component
@Slf4j
public class AdListCacheKeyGenerator implements KeyGenerator{
@Value("${zhaopin.live-environment:}")
String env;
@Override
public Object generate(Object target, Method method, Object... params) {
ListMixLiveRoomRequestBO requestBO = (ListMixLiveRoomRequestBO) params[0];
String cacheKey = new StringBuilder(env).append("_").append(requestBO.getCityId()).toString();
log.info("[cacheKeyGenerate],cacheKey={}", cacheKey);
return cacheKey;
}
}
然后@Cacheable指定该 keyGenerator
@Cacheable(keyGenerator = "adListCacheKeyGenerator")
public List<AdBO> listValidAd(ListMixLiveRoomRequestBO requestBO) {
List<AdBO> ads = thirdAdLiveRoomBusiness.listValidAd(requestBO);
setTestFlag(ads);
return ads.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ad -> ad.getId()))), ArrayList::new));
}
```
本文介绍了如何在Spring Cache中自定义@Cacheable的key,通过AdListCacheKeyGenerator组件,根据ListMixLiveRoomRequestBO的cityId生成唯一缓存键。关键步骤包括实现KeyGenerator接口和在@Cacheable注解中指定keyGenerator。
705

被折叠的 条评论
为什么被折叠?



