Java @共享缓存上的可缓存密钥?
我有一个Spring应用程序,它使用MyBatis进行持久化。我使用ehcache是因为速度对于这个应用程序很重要。我已经设置并配置了MyBatis和Ehcache。我使用一个名为“mybatis”的单一缓存,因为否则为每个实体创建单独的缓存将是荒谬的 这是我的ehcache.xmlJava @共享缓存上的可缓存密钥?,java,spring,caching,ehcache,spring-cache,Java,Spring,Caching,Ehcache,Spring Cache,我有一个Spring应用程序,它使用MyBatis进行持久化。我使用ehcache是因为速度对于这个应用程序很重要。我已经设置并配置了MyBatis和Ehcache。我使用一个名为“mybatis”的单一缓存,因为否则为每个实体创建单独的缓存将是荒谬的 这是我的ehcache.xml <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="false"
monitoring="autodetect"
dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<cache name="mybatis"
maxBytesLocalHeap="100M"
maxBytesLocalDisk="1G"
eternal="false"
timeToLiveSeconds="0"
timeToIdleSeconds="0"
statistics="true"
overflowToDisk="true"
memoryStoreEvictionPolicy="LFU">
</cache>
<cache name="jersey"
maxBytesLocalHeap="100M"
maxBytesLocalDisk="1G"
eternal="false"
timeToLiveSeconds="600"
timeToIdleSeconds="300"
statistics="true"
overflowToDisk="true"
memoryStoreEvictionPolicy="LFU">
</cache>
</ehcache>
这是我的mybatis映射器界面的一个示例
import java.util.List;
public interface InstitutionMapper {
@Cacheable(value = "mybatis")
List<Institution> getAll();
@Cacheable(value = "mybatis", key = "id")
Institution getById(long id);
@CacheEvict(value = "mybatis")
void save(Institution institution);
@CacheEvict(value = "mybatis", key = "id")
void delete(long id);
}
import java.util.List;
公共接口机构映射器{
@可缓存(value=“mybatis”)
List getAll();
@可缓存(value=“mybatis”,key=“id”)
机构getById(长id);
@cacheexecute(value=“mybatis”)
无效保存(机构);
@cacheexecute(value=“mybatis”,key=“id”)
作废删除(长id);
}
因为我有一个共享缓存,所以我需要一种方法使我的密钥对域对象是唯一的。作为保存或删除的示例,我需要清除缓存,以便新值显示在UI上。但是,我不想清除整个缓存。我不知道如何处理这个问题,这样当调用delete并退出缓存时,只有带有该ID的for机构的mybatis缓存中的条目才会被清除
密钥需要类似于域名+参数。作为一个例子,机构+id。希望这是有意义的
我看了这篇文章,但它似乎是按类名+方法+参数进行的。为整个域模型指定一个区域有点奇怪(至少可以这么说)。我可以想象,您可以在同一个缓存中收集具有相似语义的对象类型,但不是所有对象类型。如果你有一个适当的界限,你在这里提出的大多数问题都会自行解决 但是为了解释,这里有一些想法 您的
getAll()
需要密钥。如果不提供参数,则基本上任何其他无参数的@Cacheable
方法都会与缓存中的同一个键冲突
@Cacheable(value = 'mybatis', key = "'institutions'")
List<Institution> getAll();
(但这并不能解决getAll()
不一致的问题)
您的getById
不需要密钥,因为您在那里的唯一方法参数是id。回到您最初的“问题”上,如果您想在密钥前面加上前缀,您需要全面执行(以便逐出操作对同一个密钥有效)。我不会在斯佩尔这样做,因为忘记一个案例的机会太高了
您可以实现一个自定义的keyrolver
,并根据方法的返回类型附加一个唯一的前缀
话虽如此,您的示例代码几乎完全错了,因此我建议您查看,感谢您的详细解释。听起来单个缓存不是一个好主意,也不是常见做法。我认为最好使用单独的缓存区域,或者在MyBatis mapper文件中使用MyBatis ehcache支持。
@CacheEvict(value = "mybatis", key = "#p0.id")
void save(Institution institution);