两级缓存框架之j2cache的基本使用

3,385 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天,点击查看活动详情

j2cache概述

j2cache是两级缓存框架,两级缓存结构如下:

L1: 进程内缓存 caffeine/ehcache

L2: 集中式缓存 Redis/Memcached


j2cache将Ehcache、Caffeine、redis、Spring Cache等进行整合。数据读取顺序 -> L1 -> L2 -> DB

由于大量的缓存读取会导致L2的网络成为整个系统的瓶颈,因此L1的目标是降低对L2的读取次数。

该缓存框架主要用于集群环境中。单机也可使用,用于避免应用重启导致的ehcache缓存数据丢失。

SpringBoot集成J2cache

添加依赖

<dependency>
    <groupId>net.oschina.j2cache</groupId>
    <artifactId>j2cache-spring-boot2-starter</artifactId>
    <version>2.8.0-release</version>
</dependency>
<dependency>
    <groupId>net.oschina.j2cache</groupId>
    <artifactId>j2cache-core</artifactId>
    <version>2.8.0-release</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

添加配置

server:
  port: 9000

spring:
  redis:
    host: IP
    password:
    port: 6379
    database: 0

j2cache:
  # 缓存清除模式
  # active:主动清除,二级缓存过期主动通知各节点清除,优点在于所有节点可以同时收到缓存清除
  # passive:被动清除,一级缓存过期进行通知各节点清除一二级缓存
  # blend:两种模式一起运作,对于各个节点缓存准确性以及及时性要求高的可以使用(推荐使用前面两种模式中一种)
  cache-clean-mode: passive
  allow-null-values: true
  redis-client: lettuce #指定redis客户端使用lettuce,也可以使用Jedis
  l2-cache-open: true #开启二级缓存
  # 使用springRedis进行广播通知缓失效
  broadcast: net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy
  L1: #指定一级缓存提供者为caffeine
    provider_class: caffeine
  L2: #使用springRedis替换二级缓存 指定二级缓存提供者为redis
    provider_class: net.oschina.j2cache.cache.support.redis.SpringRedisProvider
    # 如果要使用lettuce客户端请配置为lettuce
    config_section: lettuce
  sync_ttl_to_redis: true
  default_cache_null_object: false
  serialization: fst  #序列化方式:fst、kyro、Java 区别:存储字节大小
caffeine:
  properties: /caffeine.properties

lettuce:
  mode: single
  namespace:
  storage: generic
  channel: j2cache
  scheme: redis
  hosts: IP:6379
  password:
  database: 0
  sentinelMasterId:
  maxTotal: 100
  maxIdle: 10
  minIdle: 10
  timeout: 10000

创建缓存配置文件

创建/resources/caffeine.properties文件

名称=缓存个数,过期时间
# [name] = size, xxxx[s|m|h|d]

default=2000, 2h
web=50, 2h

使用缓存

@RestController
@RequestMapping("/cache")
public class CacheController {

    private final String key = "myKey";

    private String region = "web";

    @Autowired
    private CacheChannel cacheChannel;

    /**
     * 设置缓存或从缓存取值
     *
     * @return
     */
    @GetMapping("/getData")
    public List<String> getInfos() {
        CacheObject cacheObject = cacheChannel.get(region, key);
        if (cacheObject.getValue() == null) {
            //缓存中没有找到,查询数据库获得
            List<String> data = new ArrayList<String>();
            data.add("info1");
            data.add("info2");
            //放入缓存
            cacheChannel.set(region, key, data);
            return data;
        }
        return (List<String>) cacheObject.getValue();
    }

    /**
     * 清理指定缓存
     *
     * @return
     */
    @GetMapping("/evict")
    public String evict() {
        cacheChannel.evict(region, key);
        return "evict success";
    }

    /**
     * 检测存在那级缓存
     *
     * @return
     */
    @GetMapping("/check")
    public String check() {
        int check = cacheChannel.check(region, key);
        return "level:" + check;
    }

    /**
     * 检测缓存数据是否存在
     *
     * @return
     */
    @GetMapping("/exists")
    public String exists() {
        boolean exists = cacheChannel.exists(region, key);
        return "exists:" + exists;
    }

    /**
     * 清理指定区域的缓存
     *
     * @return
     */
    @GetMapping("/clear")
    public String clear() {
        cacheChannel.clear(region);
        return "clear success";
    }
}