springboot j2cache 使用redis做2级缓存

依赖

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

yml

spring:
  cache:
    type: GENERIC
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: 
    username:
    password: 
  redis:
    # Redis数据库索引(默认为0)
    database: 
    # Redis服务器地址
    host: 
    # Redis服务器连接端口
    port: 6379
    # Redis服务器连接密码(默认为空)
    password: 
    jedis:
      pool:
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 8
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池中的最小空闲连接
        min-idle: 0

    # 连接超时时间(毫秒)
    timeout: 3000

j2cache:
  #  config-location: /j2cache.properties
  open-spring-cache: true
  cache-clean-mode: passive
  allow-null-values: true
  redis-client: lettuce #指定redis客户端使用lettuce,也可以使用Jedis
  l2-cache-open: true #开启二级缓存
  broadcast: net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy
  #  broadcast: jgroups
  L1: #指定一级缓存提供者为caffeine
    provider_class: caffeine
  L2: #指定二级缓存提供者为redis
    provider_class: net.oschina.j2cache.cache.support.redis.SpringRedisProvider
    config_section: lettuce
  sync_ttl_to_redis: true
  default_cache_null_object: false
  serialization: fst
caffeine:
  properties: /caffeine.properties   # 这个配置文件需要放在项目中
lettuce:
  mode: single
  namespace:
  storage: generic
  channel: j2cache
  scheme: redis
  hosts: 127.0.0.16379
  password: 111
  database: 0
  sentinelMasterId:
  maxTotal: 100
  maxIdle: 10
  minIdle: 10
  timeout: 10000
    

resources下创建 caffeine.properties

#########################################
# Caffeine configuration
# [name区域] = size缓存数量, xxxx[s秒|m分钟|h小时|d天]
#########################################
default=2000, 2h    #默认区域  最多载入2000缓存  2小时失效时间
rx=50, 2h
rx2=100, 3d

使用

import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.CacheObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.*;

/**
 * 使用j2catch提供的CacheChannel对象操作缓存数据
 */
@RestController
@RequestMapping("/cache")
public class UserController {
    private String key = "myKey";
    private String rx_2m="rx_2m";
    private String rx_30s="rx_30s";
    @Autowired
    private CacheChannel cacheChannel;

    @GetMapping("/getInfos")
    public List<String> getInfos(){
        //从缓存中获取数据,需要指定区域region和key
        CacheObject cacheObject = cacheChannel.get(rx_2m, key);
        if(cacheObject.getValue() == null){
            //缓存中没有找到,查询数据库获得
            List<String> data = new ArrayList<String>();
            data.add("info1");
            data.add("info2");
            //放入缓存
            cacheChannel.set(rx_2m,key,data);
            return data;
        }
        return (List<String>) cacheObject.getValue();
    }

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

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

    //检查指定的缓存数据是否存在
    @GetMapping("/exists")
    public boolean exists(){
        boolean exists = cacheChannel.exists(rx_2m, key);
        return exists;
    }

    //检查指定的缓存数据是从哪一级缓存获取到的
    @GetMapping("/check")
    public String check(){
        int level = cacheChannel.check(rx_2m, key);
        return "level:" + level;
    }

    //返回所有的缓存区域
    @GetMapping("/region")
    public String region(){
        Collection<CacheChannel.Region> regions = cacheChannel.regions();
        regions.stream().forEach(i->{
            System.out.println(i.toString());
        });
        return "OK";
    }
    //返回所有的缓存区域
    @GetMapping("/removeRegion")
    public String removeRegion(String region){
         cacheChannel.removeRegion(region);
        return "OK";
    }

    //批量插入数据
    @GetMapping("/set")
    public String set(){
        Map<String,Object> map=new HashMap<>();
        map.put("myKeys1","wefwjkyervweiotyeiutybeiutyeiut");
        map.put("myKeys2",14141424);
        map.put("myKeys2",new ObjUser());
        //插入1条数据
        cacheChannel.set(rx_30s,"testKey","myString");
        //批量插入数据
        cacheChannel.set(rx_2m,map);
        //带失效时间的批量缓存数据插入 注意:强烈不推荐使用带 TTL 的 set 方法,所有的缓存 TTL 都应该预先配置好,避免多个节点的缓存 Region 配置不同步
        return "OK";
    }




}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值