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

}
相关推荐
诺浅5 小时前
AWS S3 SDK FOR JAVA 基本使用及如何兼容七牛云
java·spring boot·aws
奈斯ing7 小时前
【prometheus+Grafana篇】基于Prometheus+Grafana实现Redis数据库的监控与可视化
数据库·redis·缓存·grafana·prometheus
野生技术架构师8 小时前
SpringBoot集成Tess4j :低成本解锁OCR 图片识别能力
spring boot·后端·ocr
sg_knight8 小时前
Ribbon负载均衡实战指南:7种策略选择与生产避坑
java·spring boot·spring·spring cloud·微服务·ribbon·负载均衡
猩猩之火8 小时前
XWPFTemplate生成word
spring boot·word·动态word
述雾学java9 小时前
Spring Boot + Vue 前后端分离项目解决跨域问题详解
vue.js·spring boot·后端
酷爱码9 小时前
Spring Boot 中实现 HTTPS 加密通信及常见问题排查指南
spring boot·后端·https
寒冰碧海9 小时前
Spring Boot循环依赖全场景解析与终极解决方案
java·spring boot·后端
bing_1589 小时前
Spring Boot 如何自动配置 MongoDB 连接?可以自定义哪些配置?
spring boot·后端·mongodb
慌糖9 小时前
Spring Boot 分层架构与数据流转详解
spring boot·后端·架构