ehcache3多级缓存应用

项目中如果有使用大量的本地缓存场景,可以使用redis+ehcache组合缓存,优先使用ehcache本地缓存,本地缓存没有查询到再使用redis缓存

可看前文中如何集成

本地缓存使用存在的问题

1、本地缓存如何保证缓存的是最新值

可定义版本号、自增id或者时间戳,进行判断比对是否是最新值

2、各个节点保证本地缓存一致性

保证各个节点的一致性,且不影响性能,常使用消息进行发布订阅或者是广播模式进行同步

c 复制代码
public class CustomerCache implements org.springframework.cache.Cache {
	void evict(Object key);
	void put(Object key, @Nullable Object value);
	<T> T get(Object key, Callable<T> valueLoader);
}

针对以上3个主要方法,

PUT
c 复制代码
void put(Object key, @Nullable Object value){
	 // 数据都得保存一份到redis
	 boolean success = redis.put(key, expire, value);
	 // 存入版本号 
	  redis.put(newKey, expire, remoteVersion);
	  // 以上2步骤应开启redis事务,或可存入hset格式
      
	 Long remoteVersion = getRemoteVersion(key);
   
	 if (success) {
	 	 // 存入本地缓存
	 	 ehCacheClient.put(cacheName, prefix + key, remoteVersion);
	 	 ehCacheClient.put(cacheName, key, value);
		
		// 发出消息,message需包含key remoteVersion,操作类型,put或delete
		messageService.send(topic, message);
		// 注册消息监听
		messageService.registerMessageListener(message -> {
			//删除缓存
			if (operate == delete) {
				ehCacheClient.remove(cacheName, key);
				ehCacheClient.remove(cacheName, prefix + key);
				return;
			}
			// 更新缓存
			Long localVersion = ehCacheClient.get(cacheName, prefix + key);
			if (remoteVersion > localVersion) {
			
				ehCacheClient.put(cacheName, key, remoteValue);
				ehCacheClient.put(cacheName, prefix + key, remoteVersion);
			}
		});
	 }


}
GET
c 复制代码
<T> T get(Object key, Callable<T> valueLoader){
	value = (T) ehCacheClient.get(cacheName, key)
	if (value == null) {
		value = redis.get(key);
		// 重新增加本地缓存
		ehCacheClient.put(cacheName, key, value);
		ehCacheClient.put(cacheName, prefix + key, value);
	}

}
EVICT
c 复制代码
void evict(Object key){
	
	ehCacheClient.remove(cacheName, key);
	ehCacheClient.remove(cacheName, prefix + key);
	redis.remote(key);
	// 同步到其他节点	
	messageService.send(topic, message);

}
相关推荐
摇滚侠7 分钟前
《SpringBoot 3:入门与应用实战》第 14 章 打包与部署 制作 Docker 镜像 阅读笔记 43
spring boot·笔记·docker
xiaoqiMikko2 小时前
七条 advisory 各给了一个修复版,而一次修完的那个数字一条都没写
java·spring boot
凯哥Java2 小时前
System.setProperty 的正确姿势:Spring Boot 启动类里的“缺省值“魔法
java·spring boot·后端
hui-梦苑3 小时前
[Gromacs]核心性能梯度测试:GROMACS 多线程性能调优实验
缓存·性能优化·多线程·gromacs·动力学模拟
Lyyaoo.4 小时前
【链表】【中等】两数相加/倒N删除/两个交换/排序链表/LRU缓存
数据结构·链表·缓存
努力努力再努力wz5 小时前
【Redis入门系列】:从 RESP 协议到 redis-plus-plus:Redis 客户端编程与 C++ 接口设计
开发语言·数据库·c++·redis·分布式·缓存·架构
Dreams_l5 小时前
RabbitMQ在SpringBoot中的应用
spring boot·rabbitmq·java-rabbitmq
计算机学姐5 小时前
基于SpringBoot的高校爱心慈善管理系统
java·vue.js·spring boot·后端·spring·tomcat·mybatis
vx+_bysj68695 小时前
springboot 旅行小程序97353
spring boot·后端·小程序·旅行小程序
都叫我大帅哥5 小时前
Apache Tika 4.0 正式发布:RAG 时代文件解析的终极答案
java·spring boot·spring