关于java:性能提升扩展-Spring-Cache-支持多级缓存

28次阅读

共计 3036 个字符,预计需要花费 8 分钟才能阅读完成。

为什么多级缓存

缓存的引入是当初大部分零碎所必须思考的

  • redis 作为罕用中间件,尽管咱们个别业务零碎(毕竟业务量无限)不会遇到如下图 在随着 data-size 的增大和数据结构的简单的造成性能降落,但网络 IO 耗费会成为整个调用链路中不可漠视的局部。尤其在 微服务架构中,一次调用往往会波及屡次调用 例如 pig oauth2.0 的 client 认证

  • Caffeine 来自将来的本地内存缓存, 性能比方常见的内存缓存实现性能高出不少具体比照。

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

设计难点

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

  • Spring Cache 仅反对 繁多的缓存起源,即:只能抉择 Redis 实现或者 Caffeine 实现,并不能同时应用。
  • 数据一致性:各层缓存之间的数据一致性问题,如应用层缓存和分布式缓存之前的数据一致性问题。
  • 缓存过期:Spring Cache 不反对被动的过期策略

业务流程

如何应用

    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
Benchmark Mode Cnt Score Units
多级实现 thrpt 2 2716.074 ops/s
默认 redis thrpt 2 1373.476 ops/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/m…
](https://github.com/pig-mesh/m…

https://gitee.com/log4j/pig

正文完
 0