• springboot-3-整合ehcache缓存


    整合ehcache

    1、maven引入

        <!-- Spring Boot 缓存支持启动器 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-cache</artifactId>
            </dependency>
            <!-- Ehcache 坐标 -->
            <dependency>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache</artifactId>
            </dependency>

    2、ehcache.xml 配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
             updateCheck="false">
    <cache
            name="student"
            eternal="false"
            maxElementsInMemory="100"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="300"
            memoryStoreEvictionPolicy="LRU" />
    </ehcache>
    maxElementsInMemory:
    内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况
    overflowToDisk:
    若overflowToDisk为true,则会将cache中多出的元素放入磁盘文件中,
    若为false,则会:根据memoryStoreEvictionPolicy策略替换cache中原有的元素
    eternal:
    缓存中对象是否永久有效
    timeToIdleSeconds:
    缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除
    timeToLiveSeconds:
    缓存数据的总的存活时间(单位:秒),仅当eternal=false时使用,从创建开始计时,失效结束。
    memoryStoreEvictionPolicy:
    内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存  共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)
    **可以配置多个缓存

    3、appliocation.properties配置

    #ehcache
    spring.cache.ehcache.config=classpath:ehcache.xml
    spring.cache.cache-names=student

    这里 classpath:ehcache.xml 是第二步的ehcache配置文件的路径,放在类路径下。

    student 是配置文件里命名的缓存名,可配置多个,用","逗号分隔

    4、开启缓存

    在springboot启动类上,添加@EnableCaching注解,开启缓存

    5、spring注解用法

    @Cacheable

    @CacheEvict

    @CachePut

    @Caching

    @Cacheable(value=" ",key=" ")

    value 为缓存名,key为键名。该注解注解的方法,在执行时先进缓存查看缓存中是否有键值对应元素,有则直接返回缓存中数据,无则执行方法,返回方法执行结果,并存入缓存。

    @CacheEvict(value=" ",key=" ")

    该注解通常放在delete方法上,执行时直接清理缓存中key对应键值的的元素。

    @CachePut

    该注解不会影响方法的执行,每次方法执行后将执行结果存入缓存,以key值为键

    @Caching

    该注解注解的方法执行时会直接清空缓存。

  • 相关阅读:
    实验一 开发环境的熟悉(小组)
    第六章家庭作业
    Linux常用命令-1
    Linux简介
    Python for写死循环?
    python将某个列表按元素值分成多个子列表
    xshell 5连接NAT模式的虚拟机
    python中remove的一些坑
    Sender IP字段为"0.0.0.0"的ARP请求报文
    免费ARP
  • 原文地址:https://www.cnblogs.com/yinjing/p/11168951.html
Copyright © 2020-2023  润新知