Java Spring微服务中手动发送JMS信号清除指定Hibernate二级缓存区域
手动发送Ehcache缓存清除信号及JMS消息结构解析
一、手动发送指定缓存区域的清除信号
既然你已经用了Ehcache+JMS的集成方案,要手动发清除信号,本质就是往Ehcache配置的JMS主题发送符合格式的缓存事件消息,具体步骤如下:
1. 确认目标JMS主题
先查你的Ehcache配置(不管是xml还是Java配置类),找到JMS缓存复制的主题名称,比如xml里的配置:
<cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jms.JMSCacheManagerPeerProviderFactory" properties="topicName=ehcache-replication-topic, ..." />
这里的ehcache-replication-topic就是要发送消息的目标主题。
2. 编写消息发送逻辑
用Spring的JmsTemplate就能实现,核心是构造Ehcache能识别的CacheEventMessage并序列化发送:
import org.springframework.jms.core.JmsTemplate; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.distribution.CacheEventMessage; import net.sf.ehcache.distribution.jms.JMSUtil; @Autowired private JmsTemplate jmsTemplate; @Autowired private CacheManager cacheManager; public void triggerCacheClear(String targetCacheName) { Ehcache targetCache = cacheManager.getEhcache(targetCacheName); if (targetCache == null) { throw new IllegalArgumentException("不存在指定缓存区域: " + targetCacheName); } // 构造清除整个缓存区域的事件消息 CacheEventMessage clearEvent = new CacheEventMessage( targetCache.getCacheManager().getName(), targetCacheName, CacheEventMessage.EVENT_REMOVE_ALL, // 清除全量的事件类型 null, // 单个key传null表示清除整个区域 null ); // 用Ehcache自带工具序列化消息,保证监听器能解析 byte[] serializedMsg = JMSUtil.serialize(clearEvent); // 发送到目标主题 jmsTemplate.convertAndSend("ehcache-replication-topic", serializedMsg); }
3. 关键注意事项
- 如果要清除单个key,把事件类型改成
CacheEventMessage.EVENT_REMOVE,并传入对应的key值。 - 必须用Ehcache的
JMSUtil.serialize序列化,不然订阅的服务无法识别消息格式。 - 发送的主题必须和所有微服务的Ehcache配置保持一致,否则其他节点收不到信号。
二、Ehcache JMS同步消息的性质与结构
1. 消息性质
- 序列化方式:默认用Java序列化(实现
Serializable接口),消息体是字节数组,确保跨服务的兼容性。 - 事件驱动:属于事件型消息,每个消息对应一个缓存操作(新增、删除、全量清除等),订阅方收到后同步执行对应操作。
- 发布订阅模式:Ehcache默认用JMS Topic实现,所有订阅该主题的微服务节点都会收到消息,保证集群内缓存状态一致。
2. 核心消息结构(CacheEventMessage)
Ehcache用CacheEventMessage作为缓存同步的载体,核心字段包括:
cacheManagerName:发送方的缓存管理器名称,用于区分不同缓存集群。cacheName:目标缓存区域的名称,明确要操作的缓存。event:事件类型枚举:EVENT_PUT:新增/更新缓存元素EVENT_REMOVE:删除单个缓存keyEVENT_REMOVE_ALL:清除整个缓存区域EVENT_FLUSH:刷新缓存
key:缓存key,仅EVENT_REMOVE事件有效。element:缓存元素对象,仅EVENT_PUT事件有效,包含要同步的缓存数据。
3. 传输格式
发送到JMS的消息体是CacheEventMessage序列化后的字节数组,同时Ehcache会把JMS消息的JMSType设为net.sf.ehcache.distribution.jms.JMSCacheMessage,订阅方的监听器会根据这个类型过滤处理,确保只处理Ehcache的同步消息。
内容的提问来源于stack exchange,提问作者User01
相关产品推荐
相关产品推荐

