我的 ehCache 中的冲突
Conflict in my ehCache
我在 Spring 环境中,使用 EhCache。
我有两种方法:
@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;
}
问题是当使用与第一个相同的参数调用第二个方法时,返回第一个方法的结果!
Assert.assertEquals(4, testService.add(2, 2));
Assert.assertEquals(0, testService.sub(2, 2));
Returns:
java.lang.AssertionError: expected:<0> but was:<4>
有没有关于缓存我不明白的地方?
这两个函数具有相同的参数并共享相同的 cache
实例 key
。因此,当您传递相同的参数时,它会按预期工作。 Spring 默认密钥生成器不包含方法名称。要解决此问题,请更改 cache key
或通过更改参数重载您的方法。
@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;
}
如果您想要更多自定义,您也可以创建自己的缓存密钥生成器。
看完别人的回答,我想我可以回答我自己的问题了。
如果我错了请告诉我。
这里的解决方法是以方法名为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;
}
编辑:
好的,这是完全错误的,因为现在它根本不考虑参数!
Assert.assertEquals(4, testService.add(2, 2));
Assert.assertEquals(0, testService.sub(2, 2));
Assert.assertEquals(5, testService.add(2, 3));
返回:
java.lang.AssertionError: expected:<5> but was:<4>
我在 Spring 环境中,使用 EhCache。 我有两种方法:
@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;
}
问题是当使用与第一个相同的参数调用第二个方法时,返回第一个方法的结果!
Assert.assertEquals(4, testService.add(2, 2));
Assert.assertEquals(0, testService.sub(2, 2));
Returns:
java.lang.AssertionError: expected:<0> but was:<4>
有没有关于缓存我不明白的地方?
这两个函数具有相同的参数并共享相同的 cache
实例 key
。因此,当您传递相同的参数时,它会按预期工作。 Spring 默认密钥生成器不包含方法名称。要解决此问题,请更改 cache key
或通过更改参数重载您的方法。
@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;
}
如果您想要更多自定义,您也可以创建自己的缓存密钥生成器。
看完别人的回答,我想我可以回答我自己的问题了。 如果我错了请告诉我。
这里的解决方法是以方法名为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;
}
编辑:
好的,这是完全错误的,因为现在它根本不考虑参数!
Assert.assertEquals(4, testService.add(2, 2));
Assert.assertEquals(0, testService.sub(2, 2));
Assert.assertEquals(5, testService.add(2, 3));
返回:
java.lang.AssertionError: expected:<5> but was:<4>