首页 > 其他分享 >springboot集成ehcache

springboot集成ehcache

时间:2022-09-07 17:22:39浏览次数:87  
标签:ehcache 集成 springboot cache param cacheName key String

目录

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

标签:ehcache,集成,springboot,cache,param,cacheName,key,String
From: https://www.cnblogs.com/lgxdev/p/16666583.html

相关文章

  • springboot通过注解Resource引用指定配置
    yaml配置文件中增加两个不同环境的配置:java配置文件,参考微信支付的代码:/***@author<ahref="https://github.com/binarywang">BinaryWang</a>*/@Slf4j@Config......
  • springboot的日志配置
    转载:https://blog.csdn.net/tz845195485/article/details/123361895#========================logging日志相关的配置=====================#日志级别trace<debug<inf......
  • SpringBoot解决BigDecimal传到前端后精度丢失问题
    1、局部处理(1)在相应字段上加@JsonFormat@JsonFormat(shape=JsonFormat.Shape.STRING)(2)在相应字段上加@JsonSerialize@JsonSerialize(using=ToStringSerializer.class......
  • 集成SwiftGen图片资源管理器
    1.cocoapods导入pod'SwiftGen'2.新增js脚本,在TARGETS-BuildPhaes-NewRunScriptPhase3.导入下方js语句if[[-f"${PODS_ROOT}/SwiftGen/bin/swiftgen"]];t......
  • 【AR Engine】集成AR Engine,ARSession.update方法抛出ARFatalException
    ​【问题描述】在App中接入了AREngine,在日志监控中发现个别终端用户在程序调用ARSession.update方法时,AREngine抛出了ARFatalException。通过查看日志发现,这个问题在此......
  • Simulink集成模型测试太慢怎么办?
    Tips:现阶段模型开发大部分采用Simulink,为了验证模型实现了相关功能,需要对模型进行测试。模型测试(MiL)有单元测试和集成测试之分。单元测试中模型复杂度低,信号参数数量少,测......
  • springboot集成hibernate-validator
    一、项目搭建1、使用springboot搭建一个web工程建web工程,不使用骨架创建maven的Java工程即可,不需要创建maven的web工程。2、添加父工程坐标和添加web启动器<parent>......
  • SpringBoot使用自定义注解+AOP+Redis实现接口限流
    为什么要限流系统在设计的时候,我们会有一个系统的预估容量,长时间超过系统能承受的TPS/QPS阈值,系统有可能会被压垮,最终导致整个服务不可用。为了避免这种情况,我们就需要对......
  • SpringBoot常用注解
    SpringBoot常用注解1.@SpringBootApplicationspringBoot的基石,启动类@Configuration应许spring注册额外的bean或者导入其他配置类@EnableAutoConfiguration启用Sp......
  • Springboot定义全局异常类详解
    前言当我们在开发过程中,会因为一些异常程序出现500,如果直接显示给客户看,这样很不友好。并且对我们后期维护,排查bug很困难。准备1.创建一个SpringBoot项目,引入web依赖,......