SpringCache @Cacheable keyGenerator

982 阅读1分钟

有时候我们想自定义@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));
    }
    ```