欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot2.X 整合 J2cache 一级缓存 ehcache3 二级缓存 redis (含使用demo实例)

程序员文章站 2022-04-28 18:33:04
...

1.添加依赖

		<!-- 添加ehcache支持 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
		<!-- Ehcache 坐标 -->
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>2.10.4</version>
		</dependency>
		<!--整合redis-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<version>2.1.6.RELEASE</version>
		</dependency>
		<!--整合j2cache-->
		<dependency>
			<groupId>net.oschina.j2cache</groupId>
			<artifactId>j2cache-spring-boot2-starter</artifactId>
			<version>2.7.6-release</version>
		</dependency>
		<dependency>
			<groupId>net.oschina.j2cache</groupId>
			<artifactId>j2cache-core</artifactId>
			<version>2.7.7-release</version>
		</dependency>

application.yml  增加配置

spring: 
  cache:
    ehcache:
      config: classpath:ehcache/ehcache-shiro.xml

# j2cache配置文件路径
j2cache:
  config-location: classpath:/ehcache/j2cache-${spring.profiles.active}.properties
  cache-clean-mode: active
  open-spring-cache: true

2.添加配置

配置文件结构

springboot2.X 整合 J2cache 一级缓存 ehcache3 二级缓存 redis (含使用demo实例)

ehcache-shiro.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="jeefast" updateCheck="false">

    <!-- 磁盘缓存位置 -->
    <diskStore path="java.io.tmpdir"/>
    
    <!-- maxEntriesLocalHeap:堆内存中最大缓存对象数,0没有限制 -->
    <!-- maxElementsInMemory: 在内存中缓存的element的最大数目。-->
    <!-- eternal:elements是否永久有效,如果为true,timeouts将被忽略,element将永不过期 -->
    <!-- timeToIdleSeconds:失效前的空闲秒数,当eternal为false时,这个属性才有效,0为不限制 -->
    <!-- timeToLiveSeconds:失效前的存活秒数,创建时间到失效时间的间隔为存活时间,当eternal为false时,这个属性才有效,0为不限制 -->
    <!-- overflowToDisk: 如果内存中数据超过内存限制,是否要缓存到磁盘上 -->
    <!-- statistics:是否收集统计信息。如果需要监控缓存使用情况,应该打开这个选项。默认为关闭(统计会影响性能)。设置statistics="true"开启统计 -->
    
    <!-- 默认缓存 -->
    <defaultCache
            maxEntriesLocalHeap="1000"
            eternal="false"
            timeToIdleSeconds="3600"
            timeToLiveSeconds="3600"
            overflowToDisk="false">
    </defaultCache>

    <!-- 登录记录缓存 锁定10分钟 -->
    <cache name="loginRecordCache"
           maxEntriesLocalHeap="2000"
           eternal="false"
           timeToIdleSeconds="600"
           timeToLiveSeconds="0"
           overflowToDisk="false"
           statistics="true">
    </cache>

    <!-- 系统活跃用户缓存 -->
    <cache name="sys-userCache"
           maxEntriesLocalHeap="10000"
           overflowToDisk="false"
           eternal="false"
           diskPersistent="false"
           timeToLiveSeconds="0"
           timeToIdleSeconds="0"
           statistics="true">
    </cache>

    <!-- 系统会话缓存 -->
    <cache name="shiro-activeSessionCache"
           maxElementsInMemory="10000"
           overflowToDisk="true"
           eternal="true"
           timeToLiveSeconds="0"
           timeToIdleSeconds="0"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="600">
    </cache>

</ehcache>
	

ehcache3.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- for ehcache 3.x -->
<config
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns='http://www.ehcache.org/v3'
        xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">

    <!-- Don't remote default cache configuration -->
    <cache-template name="default">
        <key-type>java.lang.String</key-type>
        <value-type>java.io.Serializable</value-type>
        <expiry>
            <ttl unit="seconds">1800</ttl>
        </expiry>
        <resources>
            <heap>1000</heap>
            <offheap unit="MB">100</offheap>
        </resources>

    </cache-template>
    <!--
    <persistence directory="${ecache.path}"/>
    -->
    <cache alias="default" uses-template="default"/>

</config>

j2cache-dev.properties

#J2Cache configuration
#j2cache 源码地址https://gitee.com/ld/J2Cache

#########################################
# Cache Broadcast Method
# values:
# jgroups -> use jgroups's multicast
# redis -> use redis publish/subscribe mechanism
#########################################
#广播策略
#j2cache.broadcast = net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy
j2cache.broadcast = redis

# 是否开启二级缓存
j2cache.l2-cache-open=true
j2cache.open-spring-cache= true
j2cache.allow-null-values= true
j2cache.cache-clean-mode= active
j2cache.redis-client=jedis

#组播的通道名称
jgroups.channel.name = j2cache

#########################################
# Level 1&2 provider
# values:
# none -> disable this level cache
# ehcache -> use ehcache2 as level 1 cache
# ehcache3 -> use ehcache3 as level 1 cache
# caffeine -> use caffeine as level 1 cache(only in memory)
# redis -> use redis(hashs) as level 2 cache
# [classname] -> use custom provider
#########################################
#一级缓存使用ehcache3
j2cache.L1.provider_class = ehcache
#j2cache.L2.provider_class = net.oschina.j2cache.cache.support.redis.SpringRedisProvider
j2cache.L2.provider_class = redis
#二级缓存使用redis
#j2cache.L2.provider_class = redis
j2cache.L2.config_section = redis

#########################################
# Cache Serialization Provider
# values:
# fst -> fast-serialization
# kyro -> kyro
# java -> java standard
# [classname implements Serializer]
#########################################

j2cache.serialization = fst

#########################################
# Ehcache configuration
#########################################

#ehcache.name=
#ehcache.configXml=/ehcache.xml
ehcache3.configXml = /ehcache/ehcache3.xml

#########################################
# Caffeine configuration
# caffeine.region.[name] = size, xxxx[s|m|h|d]
#
#########################################

caffeine.region.default = 1000, 1h 

#########################################
# Redis connection configuration
#########################################

#########################################
# Redis Cluster Mode
#
# single -> single redis server
# sentinel -> master-slaves servers
# cluster -> cluster servers (数据库配置无效,使用 database = 0)
# sharded -> sharded servers  (密码、数据库必须在 hosts 中指定,且连接池配置无效 ; redis://user:[email protected]:6379/0)
#
#########################################

#redis.mode = sentinel
redis.mode = single
#cluster name just for sharded
redis.cluster_name = mymaster

## redis cache namespace optional, default[j2cache]
redis.namespace = j2cache

## connection
#redis.hosts = 127.0.0.1:26378,127.0.0.1:26379,127.0.0.1:26380
redis.hosts = localhost:6379
redis.timeout = 2000
redis.password =
redis.database = 0

## redis pub/sub channel name
redis.channel = j2cache

## redis pool properties
redis.maxTotal = -1
redis.maxIdle = 2000
redis.maxWaitMillis = 100
redis.minEvictableIdleTimeMillis = 864000000
redis.minIdle = 1000
redis.numTestsPerEvictionRun = 10
redis.lifo = false
redis.softMinEvictableIdleTimeMillis = 10
redis.testOnBorrow = true
redis.testOnReturn = false
redis.testWhileIdle = false
redis.timeBetweenEvictionRunsMillis = 300000
redis.blockWhenExhausted = true

3.demo实例

J2cacheService.java

/**
 * @author Lion Li
 * @date 2019/10/22
 */
public interface J2cacheService {

    String addCache(String key,String value);

    String queryCache();

    String getCacheByKey(String key);

    String deleteCacheByKey(String key);
}

J2cacheServiceImpl.java

import	java.util.ArrayList;

import net.oschina.j2cache.CacheChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * @author Lion Li
 * @date 2019/10/22
 */
@Service
public class J2cacheServiceImpl implements J2cacheService {

    @Autowired
    private CacheChannel cacheChannel;

    @Override
    public String addCache(String key,String value) {
        cacheChannel.set("reg",key,value);
        return "注册:reg => key:"+key+" => value:"+value;
    }

    @Override
    public String queryCache() {
        List<String> list = new ArrayList<> ();
        Collection<String> keys = cacheChannel.keys("reg");
        for(String key : keys){
            list.add("key:"+key+" => value:"+cacheChannel.get("reg", key));
        }
        return list.toString();
    }

    @Override
    public String getCacheByKey(String key) {
        Object obj = cacheChannel.get("reg",key);
        if(obj != null){
            return obj.toString();
        }
        return "未找到";
    }

    @Override
    public String deleteCacheByKey(String key) {
        cacheChannel.evict("reg",key);
        return "删除成功";
    }
}

DemoController.java

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;

/**
 * @author Lion Li
 * @date 2019/10/22
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private J2cacheService j2cacheService;

    @GetMapping("/addCache")
    public String addCache(String key,String value){
        return j2cacheService.addCache(key,value);
    }

    @GetMapping("/queryCache")
    public String queryCache(){
        return j2cacheService.queryCache();
    }

    @GetMapping("/getCacheByKey")
    public String getCacheByKey(String key){
        return j2cacheService.getCacheByKey(key);
    }

    @GetMapping("/deleteCacheByKey")
    public String deleteCacheByKey(String key){
        return j2cacheService.deleteCacheByKey(key);
    }
}

4.测试

测试添加

springboot2.X 整合 J2cache 一级缓存 ehcache3 二级缓存 redis (含使用demo实例)

通过key获取value

springboot2.X 整合 J2cache 一级缓存 ehcache3 二级缓存 redis (含使用demo实例)

查询缓存列表

springboot2.X 整合 J2cache 一级缓存 ehcache3 二级缓存 redis (含使用demo实例)

L1为一级缓存 使用ehcache

将服务器重启 ehcache会清空 会从redis获取

springboot2.X 整合 J2cache 一级缓存 ehcache3 二级缓存 redis (含使用demo实例)

结果变为了L2 表示二级缓存 数据从redis获取 因为重启将ehcache清空了

最后测试删除

springboot2.X 整合 J2cache 一级缓存 ehcache3 二级缓存 redis (含使用demo实例)

整合测试成功