700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > SpringBoot 2.X 整合 J2cache 一级缓存 ehcache3 二级缓存 redis (含使用demo实例)

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

时间:2024-02-15 15:07:24

相关推荐

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

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}.propertiescache-clean-mode: activeopen-spring-cache: true

2.添加配置

配置文件结构

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"开启统计 --><!-- 默认缓存 --><defaultCachemaxEntriesLocalHeap="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 --><configxmlns:xsi='/2001/XMLSchema-instance'xmlns='/v3'xsi:schemaLocation="/v3 /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 源码地址/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.SpringRedisPubSubPolicyj2cache.broadcast = redis# 是否开启二级缓存j2cache.l2-cache-open=truej2cache.open-spring-cache= truej2cache.allow-null-values= truej2cache.cache-clean-mode= activej2cache.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##########################################一级缓存使用ehcache3j2cache.L1.provider_class = ehcache#j2cache.L2.provider_class = net.oschina.j2cache.cache.support.redis.SpringRedisProviderj2cache.L2.provider_class = redis#二级缓存使用redis#j2cache.L2.provider_class = redisj2cache.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.xmlehcache3.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:password@127.0.0.1:6379/0)###########################################redis.mode = sentinelredis.mode = single#cluster name just for shardedredis.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:26380redis.hosts = localhost:6379redis.timeout = 2000redis.password =redis.database = 0## redis pub/sub channel nameredis.channel = j2cache## redis pool propertiesredis.maxTotal = -1redis.maxIdle = 2000redis.maxWaitMillis = 100redis.minEvictableIdleTimeMillis = 864000000redis.minIdle = 1000redis.numTestsPerEvictionRun = 10redis.lifo = falseredis.softMinEvictableIdleTimeMillis = 10redis.testOnBorrow = trueredis.testOnReturn = falseredis.testWhileIdle = falseredis.timeBetweenEvictionRunsMillis = 300000redis.blockWhenExhausted = true

3.demo实例

J2cacheService.java

/*** @author Lion Li* @date /10/22*/public interface J2cacheService {String addCache(String key,String value);String queryCache();String getCacheByKey(String key);String deleteCacheByKey(String key);}

J2cacheServiceImpl.java

importjava.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 /10/22*/@Servicepublic class J2cacheServiceImpl implements J2cacheService {@Autowiredprivate CacheChannel cacheChannel;@Overridepublic String addCache(String key,String value) {cacheChannel.set("reg",key,value);return "注册:reg => key:"+key+" => value:"+value;}@Overridepublic 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();}@Overridepublic String getCacheByKey(String key) {Object obj = cacheChannel.get("reg",key);if(obj != null){return obj.toString();}return "未找到";}@Overridepublic 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 /10/22*/@RestController@RequestMapping("/demo")public class DemoController {@Autowiredprivate 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.测试

测试添加

通过key获取value

查询缓存列表

L1为一级缓存使用ehcache

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

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

最后测试删除

整合测试成功

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。