Spring Boot集成Ehcache 3.6:如何通过XML配置启用copyOnRead?
在Ehcache 3.6中通过XML配置实现类似copyOnRead的特性
Ehcache 3.x已经摒弃了2.x版本里的copyOnRead/copyOnWrite配置项,取而代之的是**Copier(复制器)**机制,你可以通过XML配置内置或自定义复制器,实现读取时复制数据、返回对象副本而非原引用的效果。
1. 使用内置复制器配置
Ehcache 3提供两种开箱即用的复制器:
serializing-copier:通过序列化/反序列化实现对象复制,要求目标对象实现Serializable接口cloning-copier:通过对象克隆实现复制,要求目标对象实现Cloneable接口并重写clone()方法
要启用读取时复制,需在缓存配置的<read-mode>节点中指定对应复制器,示例配置如下:
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.6.xsd"> <cache alias="yourCacheName"> <key-type>java.lang.Long</key-type> <value-type>com.yourpackage.YourSerializableObject</value-type> <resources> <heap unit="entries">1000</heap> </resources> <!-- 配置读取时使用序列化复制器,对应原copyOnRead特性 --> <read-mode> <serializing-copier/> </read-mode> <!-- 如果需要写入时也复制数据,可配置write-mode对应原copyOnWrite --> <!-- <write-mode> <serializing-copier/> </write-mode> --> </cache> </config>
2. 自定义复制器配置
如果内置复制器无法满足需求,你可以实现org.ehcache.spi.copy.Copier接口自定义复制逻辑,再在XML中注册并引用:
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.6.xsd"> <!-- 注册自定义复制器 --> <service> <copiers> <copier type="com.yourpackage.CustomCopier" alias="customCopier"/> </copiers> </service> <cache alias="yourCacheName"> <key-type>java.lang.Long</key-type> <value-type>com.yourpackage.YourObject</value-type> <resources> <heap unit="entries">1000</heap> </resources> <!-- 读取时使用自定义复制器 --> <read-mode> <copier-ref alias="customCopier"/> </read-mode> </cache> </config>
关键注意事项
<read-mode>节点的作用完全对应Ehcache 2.x的copyOnRead,配置后每次读取缓存都会返回对象副本,避免外部修改缓存内的原对象<write-mode>对应原copyOnWrite,配置后写入缓存时会先复制对象再存储,防止原对象后续修改影响缓存数据- 使用内置复制器时,必须确保对象满足对应前置条件(序列化/克隆要求),否则会抛出运行时异常
内容的提问来源于stack exchange,提问作者Eldy
相关产品推荐
相关产品推荐

