Spring cache with instance variable and parameter as key

时间秒杀一切 提交于 2020-06-17 05:38:08

问题


I am using ehcache for caching the method results. The key has to be a combination of both member object and method's parameter. My class looks something like:

Class A {

private B b;

@Cacheable(value="someCache",key="some key based on B and C")
public Result getResult(C c){
......
}

I need the key to be based on B and C. I referred https://code.google.com/p/ehcache-spring-annotations/issues/detail?id=69 but they did not specify how to include the method parameter in the key generation. Could someone help me with this?


回答1:


you can access the A object with root.target in the key. e.g.

key="#root.target.b.id+'-'+#c.id"



回答2:


I have implemented a custom key generator to solve this. Still I think this can be solved by ehcache without using a custom key generator. But i could not get the answer anywhere. Please see my answer below:

@Component
public class Home {

    private Parameter param;

    @Cacheable(cacheName = "homeCache", 
                    keyGenerator = @KeyGenerator(name = "com.myapp.cache.Home.ParamKeyGenerator"))

    public Result getPerson(Person p) {

        //Do something with p
        return result;
    }

    public Parameter getParam() {

        return param;
    }

    public void setParam(Parameter param) {

        this.param = param;
    }

    public static class ParamKeyGenerator implements CacheKeyGenerator<Serializable> {

        public Serializable generateKey(MethodInvocation methodInvocation) {

            Object[] obj = methodInvocation.getArguments();
            Home h = (Home) methodInvocation.getThis();

            return this.generateKey(obj[0], h.getParam());
        }

        public Serializable generateKey(Object... data) {

            String key = ((Person) data[0]).getName() + ((Parameter) data[1]).getName();
            System.out.println("generating key: " + key);
            return key;
        }
    }
}


来源:https://stackoverflow.com/questions/22019291/spring-cache-with-instance-variable-and-parameter-as-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!