5、springboot集成ehcache
springboot集成ehcache
ps:springboot 2.2以上
1、增加依赖
pom.xml文件中增加
<!--开启 cache 缓存 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-jgroupsreplication</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>org.jgroups</groupId> <artifactId>jgroups</artifactId> <version>3.0.9.Final</version> </dependency>
2、增加ehcache.xml
使用jgroups集群的方式
<?xml version="1.0" encoding="UTF-8"?> <ehcache name="myEncache"> <!-- diskStore:为缓存路径,ehcache分为内存和磁盘 2级,此属性定义磁盘的缓存位置 user.home - 用户主目录 user.dir - 用户当前工作目录 java.io.tmpdir - 默认临时文件路径 --> <diskStore path="D:/home/Tmp_Ehcache"/> <!-- name:缓存名称。 maxElementsInMemory:缓存最大数目 maxElementsOnDisk:硬盘最大缓存个数。 eternal:对象是否永久有效,一但设置了,timeout将不起作用。 overflowToDisk:是否保存到磁盘,当系统宕机时 timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。 timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。 diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。 diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。 memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。 clearOnFlush:内存数量最大时是否清除。 memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。 FIFO,first in first out,这个是大家最熟的,先进先出。 LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。 LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。 --> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" /> <!-- <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=manual,rmiUrls=//192.168.1.176:40001/ehcache" /> --> <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheManagerPeerProviderFactory" properties="connect=UDP(mcast_addr=224.1.1.1;mcast_port=45678;ip_ttl=32;mcast_send_buf_size=120000;mcast_recv_buf_size=80000): PING(timeout=2000;num_initial_members=2): MERGE2(min_interval=5000;max_interval=10000): FD_SOCK:VERIFY_SUSPECT(timeout=1500): pbcast.NAKACK(retransmit_timeout=3000): UNICAST(timeout=5000): pbcast.STABLE(desired_avg_gossip=20000): FRAG: pbcast.GMS(join_timeout=5000;print_local_addr=true)" propertySeparator="::" /> <!-- <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="hostName=localhost, port=40002, socketTimeoutMillis=200000"/>--> <cache name="ehcache" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" > <!-- <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true,replicateUpdatesViaCopy= false, replicateRemovals= true " /> <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=true"> </bootstrapCacheLoaderFactory>--> <cacheEventListenerFactory class="net.sf.ehcache.distribution.jgroups.JGroupsCacheReplicatorFactory" properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true, replicateUpdatesViaCopy=true, replicateRemovals=true " /> <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.jgroups.JGroupsBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=false"/> </cache> </ehcache>
3、增加配置
3.1、bootstrap.properties xml
spring.cache.ehcache.config=classpath:/ehcache.xml spring.cache.type=ehcache
3.2、启动类增加配置
@EnableCaching public class AdminServiceApplication {
4、工具类操作
import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; /** * EhCache 缓存工具类 * 使用String格式的value */ @Component public class EhcacheUtils { @Autowired private CacheManager cacheManager; // 默认的缓存存在时间(秒) private static final int DEFAULT_LIVE_SECOND = 20 * 60; public static final String EHCACHE_KEY = "ehcache"; /** * 添加缓存 * * @param cacheName xml中缓存名字 * @param key * @param value * @param timeToLiveSeconds 缓存生存时间(秒) */ public void set(String cacheName, String key, Object value, int timeToLiveSeconds) { Cache cache = cacheManager.getCache(cacheName); Element element = new Element( key, value, 0,// timeToIdleSeconds=0 timeToLiveSeconds); cache.put(element); } /** * 添加缓存 * 使用默认生存时间 * * @param cacheName xml中缓存名字 * @param key * @param value */ public void set(String cacheName, String key, Object value) { Cache cache = cacheManager.getCache(cacheName); Element element = new Element( key, value, 0,// timeToIdleSeconds DEFAULT_LIVE_SECOND); cache.put(element); } /** * 添加缓存 * * @param cacheName xml中缓存名字 * @param key * @param value * @param timeToIdleSeconds 对象空闲时间,指对象在多长时间没有被访问就会失效。 * 只对eternal为false的有效。传入0,表示一直可以访问。以秒为单位。 * @param timeToLiveSeconds 缓存生存时间(秒) * 只对eternal为false的有效 */ public void set(String cacheName, String key, Object value, int timeToIdleSeconds, int timeToLiveSeconds) { Cache cache = cacheManager.getCache(cacheName); Element element = new Element( key, value, timeToIdleSeconds, timeToLiveSeconds); cache.put(element); } /** * 添加缓存 * * @param cacheName xml中缓存名字 * @param key * @return */ public Object get(String cacheName, String key) { Cache cache = cacheManager.getCache(cacheName); Element element = cache.get(key); if (element == null) { return null; } return element.getObjectValue(); } /** * 删除缓存数据 * * @param cacheName * @param key */ public void delete(String cacheName, String key) { try { Cache cache = cacheManager.getCache(cacheName); cache.remove(key); } catch (Exception e) { } } }
5、使用
1、注入 @Autowired EhcacheUtils ehcacheUtils; 2、使用(集群获取时,需要有相同类型value才能获取到) // 获取权限信息 List<SysSaaRoleTaskVo> resList = saaRoleTaskService.findUserTaskList(sysUserVo.getUserCode()); ehcacheUtils.set(EhcacheUtils.EHCACHE_KEY,com.platform.gis.core.constant.RedisKeyConstant.TP_USER_AUTH_PREFIX + sysUser.getUserCode() + ":" + tpSessionId, JSON.toJSONString(resList));
标签:
springboot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?