Reputation: 131
I am in a Spring environement, using EhCache. I have 2 methods:
@Override
@Cacheable("myCache")
public int add(int a, int b) {
return a + b;
}
@Override
@Cacheable("myCache")
public int sub(int a, int b) {
return a - b;
}
The problem is that when the second method is called with the same argument as the first, the result from the first method is returned!
Assert.assertEquals(4, testService.add(2, 2));
Assert.assertEquals(0, testService.sub(2, 2));
Returns:
java.lang.AssertionError: expected:<0> but was:<4>
Is there something I did not understand about caching?
Upvotes: 0
Views: 365
Reputation: 589
Both functions are having same parameters and sharing the same cache
instance key
.So, it is working as expected when you pass the same arguments. Spring default key generator does not include method name. To solve this either change the cache key
or overload your method by changing parameters.
@Override
@Cacheable("myCache", key="{ #root.methodName, #a, #b }")
public int add(Integer a, Integer b) {
return a + b;
}
@Override
@Cacheable("myCache",key="{ #root.methodName, #a, #b }")
public int sub(Integer a, Integer b) {
return a - b;
}
You can also create your own cache key generator if you want more customisation.
Upvotes: 1
Reputation: 131
After reading other people answers, I think I can answer my own question. Let me klnow if I'm wrong.
The solution here is the take the method name as the key:
@Override
@Cacheable(value = "myCache", key = "#root.method.name")
public int add(int a, int b) {
return a + b;
}
@Override
@Cacheable(value = "myCache", key = "#root.method.name")
public int sub(int a, int b) {
return a - b;
}
EDIT:
Ok this is totally wrong as now it does not look at the arguments at all!
Assert.assertEquals(4, testService.add(2, 2));
Assert.assertEquals(0, testService.sub(2, 2));
Assert.assertEquals(5, testService.add(2, 3));
returned:
java.lang.AssertionError: expected:<5> but was:<4>
Upvotes: 0