Java Spring可缓存对象

Java Spring可缓存对象,java,spring,Java,Spring,使用Cacheable时,我可以执行以下操作: @Cacheable(value = CacheUtil.LEVEL1, key = "'Location'+#root.methodName+'_'+#country+'_'+#lang") public List<Location> getCities(String country, String lang) 我应该如何编写@Cacheable使其工作 谢谢 你需要这样的东西: @Cacheable(value = Cac

使用Cacheable时,我可以执行以下操作:

@Cacheable(value = CacheUtil.LEVEL1, key = "'Location'+#root.methodName+'_'+#country+'_'+#lang")
    public List<Location> getCities(String country, String lang)
我应该如何编写@Cacheable使其工作


谢谢

你需要这样的东西:

@Cacheable(value = CacheUtil.LEVEL1, keyGenerator="contentRequestKeyGenerator")
public Content getContent(ContentRequest Request)
其中contentRequestKeyGenerator是实现KeyGenerator接口的bean的名称,请参阅

在过去,我有一个bean为几个不同的缓存类生成密钥,在下面的示例中,对象[0]是调用方法的类,在您的示例中是ContentRequest:

@Component
public class MyKeyGenerator implements KeyGenerator{

    @Override
    public Object generate(Object o, Method method, Object... objects) {
        if (String.class.isInstance(objects[0])) {
            return ....
        }
        else if (....) {

    }
}
然后您将使用以下命令:

@Cacheable(value = "properties", keyGenerator = "myKeyGenerator")
public Property getProperty(String key) {

你需要这样做吗?默认值是ContentRequest的hashCode,通常这已经足够了。

我还有很多类似的类。我是否需要每个都实现上述功能?除了密钥生成器之外,您还可以使用唯一的
Request
属性作为密钥,例如
@Cacheable(value=CacheUtil.LEVEL1,key=“Request.someProperty”)public Content getContent(ContentRequest Request)
@Cacheable(value = "properties", keyGenerator = "myKeyGenerator")
public Property getProperty(String key) {