今天发现一篇多级缓存文章,觉得很有参考价值,虽然目前还没有用这种架构,但是值得学习,再这里记录一下

 

1、这里先介绍一下Caffeine 

http://www.mydlq.club/article/56/

1.1 本地缓存介绍

缓存在日常开发中启动至关重要的作用,由于是存储在内存中,数据的读取速度是非常快的,能大量减少对数据库的访问,减少数据库的压力。

之前介绍过 Redis 这种 NoSql 作为缓存组件,它能够很好的作为分布式缓存组件提供多个服务间的缓存,但是 Redis 这种还是需要网络开销,增加时耗。本地缓存是直接从本地内存中读取,没有网络开销,例如秒杀系统或者数据量小的缓存等,比远程缓存更合适。

1.2、缓存组件 Caffeine 介绍

按 Caffeine Github 文档描述,Caffeine 是基于 JAVA 8 的高性能缓存库。并且在 spring5 (springboot 2.x) 后,spring 官方放弃了 Guava,而使用了性能更优秀的 Caffeine 作为默认缓存组件。

1.2.1、Caffeine 性能

可以通过下图观测到,在下面缓存组件中 Caffeine 性能是其中最好的。

 

 

1.2.2、Caffeine 配置说明

参数 类型 描述
initialCapacity integer 初始的缓存空间大小
maximumSize long 缓存的最大条数
maximumWeight long 缓存的最大权重
expireAfterAccess duration 最后一次写入或访问后经过固定时间过期
refreshAfterWrite duration 最后一次写入后经过固定时间过期
refreshAfterWrite duration 创建缓存或者最近一次更新缓存后经过固定的时间间隔,刷新缓存
weakKeys boolean 打开 key 的弱引用
weakValues boolean 打开 value 的弱引用
softValues boolean 打开 value 的软引用
recordStats - 开发统计功能

注意:

  • weakValues 和 softValues 不可以同时使用。
  • maximumSize 和 maximumWeight 不可以同时使用。
  • expireAfterWrite 和 expireAfterAccess 同事存在时,以 expireAfterWrite 为准。

1.2.3、软引用与弱引用

  • 软引用: 如果一个对象只具有软引用,则内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。
  • 弱引用: 弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存
// 软引用
Caffeine.newBuilder().softValues().build();

// 弱引用
Caffeine.newBuilder().weakKeys().weakValues().build();

1.3、SpringBoot 集成 Caffeine 两种方式

SpringBoot 有俩种使用 Caffeine 作为缓存的方式:

  • 方式一: 直接引入 Caffeine 依赖,然后使用 Caffeine 方法实现缓存。
  • 方式二: 引入 Caffeine 和 Spring Cache 依赖,使用 SpringCache 注解方法实现缓存。

下面将介绍下,这俩中集成方式都是如何实现的。

 

2、为什么多级缓存

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

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

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

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

设计难点

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

  • Spring Cache 仅支持 单一的缓存来源,即:只能选择 Redis 实现或者 Caffeine 实现,并不能同时使用。

  • 数据一致性:各层缓存之间的数据一致性问题,如应用层缓存和分布式缓存之前的数据一致性问题。

  • 缓存过期:Spring Cache 不支持主动的过期策略

业务流程

如何使用

  • 引入依赖
<dependency>
    <groupId>com.pig4cloud.plugin</groupId>
    <artifactId>multilevel-cache-spring-boot-starter</artifactId>
    <version>0.0.1</version>
</dependency>
复制代码
  • 开启缓存支持
@EnableCaching
public class App {
 public static void main(String[] args) {
  SpringApplication.run(App.class, args);
 }
}
复制代码
  • 目标接口声明 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

Benchmark Mode Cnt Score Units
多级实现 thrpt 2 2716.074 ops/s
默认 redis thrpt 2 1373.476 ops/s

代码原理

  • 自定义 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;
 }
}
复制代码
  • 多级读取、过期策略实现
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;
 }
}
复制代码
  • 过期策略,所有更新操作都基于 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);
 }
}
复制代码
  • 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());
 }
}
复制代码

参考

源码地址

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

gitee.com/log4j/pig

资料

http://www.mydlq.club/article/56/

https://juejin.im/post/6877328415729549320
 

Logo

云原生社区为您提供最前沿的新闻资讯和知识内容

更多推荐