「性能提升」扩展 Spring Cache 支持多级缓存

摘要:
设计难点目前,大多数应用程序缓存都是基于SpringCache实现的,注释缓存技术存在以下问题:SpringCache只支持单个缓存源,即只能选择Redis实现或Caffeine实现,不能同时使用。缓存过期:SpringCache不支持活动过期策略。如何使用业务流程引入依赖项<dependency><groupId>com.pig4cloud.plugin</groupId><artifactId>多级缓存弹簧根启动程序</artifactId><version>0.0.1</version></adependency˃启用缓存支持@EnableCachingpublicclassApp{publicstaticvoidmain{SpringApplication.run;}}目标接口声明SpringCache annotation@Cacheable@GetMappingpublicStringget{return“success”;}性能比较是为了确保Redis在127.0.0.1循环_11上安装OS:mcOSMoveCPU:2.3GHz IntelCorei5RAM:8GB2133MHzLPDDR3JVM:coretto。jdkBenchmarkModeCntScoreUnits多级实现thropt22716.074ops/s默认redishrpt21373.476ops/s代码原理用户定义的CacheManager多级缓存实现publicclassRedisCafeineCacheManagementsCacheManager{@OverridepublicCachegetCache{CacheCache=cacheMap.get;if(cache!cache:oldCache;}}多级读取和过期策略实现publicclassRedisCafeineCacheextendsAbstractValueAdaptingCache{protectedObjectlookup{ObjectcacheKey=getKey;//1。首先调用缓存以查询指定的值Objectvalue=cachecache.getIfPresent;if(值!

为什么多级缓存

缓存的引入是现在大部分系统所必须考虑的

  • redis 作为常用中间件,虽然我们一般业务系统(毕竟业务量有限)不会遇到如下图 在随着 data-size 的增大和数据结构的复杂的造成性能下降,但网络 IO 消耗会成为整个调用链路中不可忽视的部分。尤其在 微服务架构中,一次调用往往会涉及多次调用 例如pig oauth2.0 的 client 认证

「性能提升」扩展 Spring Cache 支持多级缓存第1张

  • Caffeine 来自未来的本地内存缓存,性能比如常见的内存缓存实现性能高出不少详细对比

「性能提升」扩展 Spring Cache 支持多级缓存第2张

综合所述:我们需要构建 L1 Caffeine JVM 级别缓存 , L2 Redis 缓存。

设计难点

目前大部分应用缓存都是基于 Spring Cache 实现,基于注解(annotation)的缓存(cache)技术,存在的问题如下:

  • Spring Cache 仅支持 单一的缓存来源,即:只能选择 Redis 实现或者 Caffeine 实现,并不能同时使用。
  • 数据一致性:各层缓存之间的数据一致性问题,如应用层缓存和分布式缓存之前的数据一致性问题。
  • 缓存过期:Spring Cache 不支持主动的过期策略

业务流程

「性能提升」扩展 Spring Cache 支持多级缓存第3张

如何使用

    1. 引入依赖
<dependency>
    <groupId>com.pig4cloud.plugin</groupId>
    <artifactId>multilevel-cache-spring-boot-starter</artifactId>
    <version>0.0.1</version>
</dependency>
    1. 开启缓存支持
@EnableCaching
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}
    1. 目标接口声明 Spring Cache 注解
@Cacheable(value = "get",key = "#key")
@GetMapping("/get")
public String get(String key){
    return "success";
}

性能比较

为保证性能 redis 在 127.0.0.1 环路安装

  • OS: macOS Mojave
  • CPU: 2.3 GHz Intel Core i5
  • RAM: 8 GB 2133 MHz LPDDR3
  • JVM: corretto_11.jdk
BenchmarkModeCntScoreUnits
多级实现thrpt22716.074ops/s
默认 redisthrpt21373.476ops/s

代码原理

    1. 自定义 CacheManager 多级缓存实现
public class RedisCaffeineCacheManager implements CacheManager {

	@Override
	public Cache getCache(String name) {
		Cache cache = cacheMap.get(name);
		if (cache != null) {
			return cache;
		}
		cache = new RedisCaffeineCache(name, stringKeyRedisTemplate, caffeineCache(), cacheConfigProperties);
		Cache oldCache = cacheMap.putIfAbsent(name, cache);
		log.debug("create cache instance, the cache name is : {}", name);
		return oldCache == null ? cache : oldCache;
	}
}
    1. 多级读取、过期策略实现
public class RedisCaffeineCache extends AbstractValueAdaptingCache {
	protected Object lookup(Object key) {
		Object cacheKey = getKey(key);

    // 1. 先调用 caffeine 查询是否存在指定的值
		Object value = caffeineCache.getIfPresent(key);
		if (value != null) {
			log.debug("get cache from caffeine, the key is : {}", cacheKey);
			return value;
		}

    // 2. 调用 redis 查询在指定的值
		value = stringKeyRedisTemplate.opsForValue().get(cacheKey);

		if (value != null) {
			log.debug("get cache from redis and put in caffeine, the key is : {}", cacheKey);
			caffeineCache.put(key, value);
		}
		return value;
	}
}
    1. 过期策略,所有更新操作都基于 redis pub/sub 消息机制更新
public class RedisCaffeineCache extends AbstractValueAdaptingCache {
	@Override
	public void put(Object key, Object value) {
		push(new CacheMessage(this.name, key));
	}

	@Override
	public ValueWrapper putIfAbsent(Object key, Object value) {
				push(new CacheMessage(this.name, key));
	}

	@Override
	public void evict(Object key) {
		push(new CacheMessage(this.name, key));
	}

	@Override
	public void clear() {
		push(new CacheMessage(this.name, null));
	}

	private void push(CacheMessage message) {
		stringKeyRedisTemplate.convertAndSend(topic, message);
	}
}
    1. MessageListener 删除指定 Caffeine 的指定值
public class CacheMessageListener implements MessageListener {

	private final RedisTemplate<Object, Object> redisTemplate;

	private final RedisCaffeineCacheManager redisCaffeineCacheManager;

	@Override
	public void onMessage(Message message, byte[] pattern) {
		CacheMessage cacheMessage = (CacheMessage) redisTemplate.getValueSerializer().deserialize(message.getBody());
				cacheMessage.getCacheName(), cacheMessage.getKey());
		redisCaffeineCacheManager.clearLocal(cacheMessage.getCacheName(), cacheMessage.getKey());
	}
}

源码地址

https://github.com/pig-mesh/multilevel-cache-spring-boot-starter

https://gitee.com/log4j/pig

项目推荐: Spring Cloud 、Spring Security OAuth2的RBAC权限管理系统 欢迎关注

免责声明:文章转载自《「性能提升」扩展 Spring Cache 支持多级缓存》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇nmap命令详解HTML5 本地文件操作之FileSystemAPI整理(一)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Redis缓存设计和问题处理

工作中做的所有项目都用到了redis,对其设计思路和问题处理做个总结。 key设计:可读性高,定义简洁,不包含特殊字符,一般使用:分隔,比如user:info:1000001,表示id为1000001的缓存key value设计:字符串不宜过长,字符串最大是512M,一般来说超过10k我们就认为他是bigkey,集合,有序集合,哈希,个数不宜太多,比如存储...

PHP解决网站大流量与高并发

1:硬件方面   普通的一个p4的服务器每天最多能支持大约10万左右的IP,如果访问量超过10W那么需要专用的服务器才能解决,如果硬件不给力 软件怎么优化都是于事无补的。主要影响服务器的速度 有:网络-硬盘读写速度-内存大小-cpu处理速度。 2:软件方面     第一个要说的就是数据库   首先要有一个很好的架构,查询尽量不用* 避免相关子查询 给经常查...

nginx 配置的一些参数

/etc/nginx/nginx.conf worker_rlimit_nofile#;      --指定一个worker 进程所能打开的最大文件描述符数量worker_rlimit_sigpending#;    --指定每个用户能够发往进程的信号的数量 性能优化相关的配置  1.work_processes      --worker 进程的个数,通...

EhCache之最简单的缓存框架

一、简介 Ehcache是一个用Java实现的使用简单,高速,实现线程安全的缓存管理类库,ehcache提供了用内存,磁盘文件存储,以及分布式存储方式等多种灵活的cache管理方案。同时ehcache作为开放源代码项目,采用限制比较宽松的Apache License V2.0作为授权方式,被广泛地用于Hibernate, Spring,Cocoon等其他...

前端缓存最佳实践

前言 缓存,这是一个老生常谈的话题,也常被作为前端面试的一个知识点。 本文,重点在与探讨在实际项目中,如何进行缓存的设置,并给出一个较为合理的方案。 强缓存和协商缓存 在介绍缓存的时候,我们习惯将缓存分为强缓存和协商缓存两种。两者的主要区别是使用本地缓存的时候,是否需要向服务器验证本地缓存是否依旧有效。顾名思义,协商缓存,就是需要和服务器进行协商,最终确定...

7.模块化封装Storage实现缓存数据持久化

1.模块化封装Storage实现缓存数据持久化 1.在src目录下新建目录model,在model目录下新建js文件取名storage.js var storage={ set(key,value){ // 设置为本地缓存方法 localStorage.setItem(key,JSON.stringify(valu...