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);

}
相关推荐
a56299161934 分钟前
【springboot】Spring 官方抛弃了 Java 8!新idea如何创建java8项目
java·spring boot·spring
lcrml3 小时前
Redis简介、常用命令及优化
数据库·redis·缓存
编程小风筝3 小时前
如何用redission实现springboot的分布式锁?
spring boot·分布式·后端
代码探秘者3 小时前
【大模型应用】4.分块之六大策略
java·数据结构·后端·python·spring
码喽7号3 小时前
Springboot学习六:MybatisPlus的多表查询以及分页查询
java·spring boot·学习
那我掉的头发算什么3 小时前
【博客系统】基于Spring全家桶的博客系统(下)
java·后端·spring·mybatis·开发
独自破碎E3 小时前
【面试真题拆解】Spring中的注解
数据库·spring·面试
不吃香菜学java3 小时前
苍穹外卖-新增菜品需求分析
java·spring boot·spring·tomcat·maven·ssm
JavaGuide4 小时前
美团面试:为什么要用分布式缓存?本地缓存呢?多级缓存一致性如何保证?
数据库·redis·后端·缓存·大厂面试
一个有温度的技术博主4 小时前
Redis系列四:redis的启动配置
数据库·redis·缓存