springboot ehcache《二》

package com.wangbiao.controller;

import com.wangbiao.controller.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EhcacheDemo {

   @Autowired
   private   DemoService demoService;

    /**
     * @Cacheable
     *表明所修饰的方法是可以缓存的:当第一次调用这个方法时,
     * 它的结果会被缓存下来,在缓存的有效时间内,
     * 以后访问这个方法都直接返回缓存结果,不再执行方法中的代码段。
     *
     *value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name,
     * 指明将值缓存到哪个Cache中
     *
     key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,
     * 支持SpEL,如果要引用参数值使用井号加参数名,如:#userId,
     * 一般来说,我们的更新操作只需要刷新缓存中某一个值,所以定义缓存的key值的方式就很重要,
     * 最好是能够唯一,因为这样可以准确的清除掉特定的缓存,而不会影响到其它缓存值
     * @param userId
     * @return
     */
    @GetMapping("/getuserId")
    public String get(@RequestParam("userId") String userId){
        return demoService.get(userId);
    }


    @GetMapping("/param")
    public String getTimestamp(@RequestParam("param") String param){
        return demoService.getTimestamp(param);
    }


    @GetMapping("/key")
    @Cacheable(value="HelloWorldCache", key="#key")
    public String getDataFromDB(String key) {
        System.out.println("从数据库中获取数据...");
        return key + ":" + String.valueOf(Math.round(Math.random()*1000000));
    }

    /**
     * @CacheEvict
     与@Cacheable功能相反,@CacheEvict表明所修饰的方法是用来删除失效或无用的缓存数据
     * @param key
     */
    @GetMapping("/key1")
    @CacheEvict(value="HelloWorldCache", key="#key")
    public void removeDataAtDB(String key) {
        System.out.println("从数据库中删除数据");
    }


    /**
     * @CachePut
     *@Cacheable不同,@CachePut不仅会缓存方法的结果,还会执行方法的代码段。
     * 它支持的属性和用法都与@Cacheable一致。
     * @param key
     * @return
     */
    @GetMapping("/key2")
    @CachePut(value="HelloWorldCache", key="#key")
    public String refreshData(String key) {
        System.out.println("模拟从数据库中加载数据");
        return key + "::" + String.valueOf(Math.round(Math.random()*1000000));
    }

    @GetMapping("/key3")
    @Cacheable(value="UserCache", key="'user:' + #userId")
    public Object findById(String userId) {
        System.out.println("模拟从数据库中查询数据");
        return  "ssss";
    }

    /**
     *  condition:触发条件,只有满足条件的情况才会清除缓存,默认为空,支持SpEL
     * @param userId
     * @return
     */
    @GetMapping("/key4")
    @Cacheable(value="UserCache", condition="#userId.length()<12")
    public boolean isReserved(String userId) {
        System.out.println("UserCache:"+userId);
        return false;
    }


    /**
     *      value:缓存位置名称,不能为空,同上
     *     key:缓存的key,默认为空,同上
     *     condition:触发条件,只有满足条件的情况才会清除缓存,默认为空,支持SpEL
     *     allEntries:true表示清除value中的全部缓存,默认为false
     * @param userId
     */
    @GetMapping("/key5")
    //清除掉UserCache中某个指定key的缓存
    @CacheEvict(value="UserCache",key="'user:' + #userId")
    public void removeUser(String userId) {
        System.out.println("UserCache remove:"+ userId);
    }

    //allEntries:true表示清除value中的全部缓存,默认为false
    //清除掉UserCache中全部的缓存
    @GetMapping("/key6")
    @CacheEvict(value="UserCache", allEntries=true)
    public void removeAllUser() {
        System.out.println("UserCache delete all");
    }
}
<?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"><!--    每次启动都会访问官方网站查看是否有最新版本  设置为false-->

    <diskStore path="C:/Users/72784/Desktop/eaaaa"/>
    <!-- 默认缓存 -->
    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

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


    <!-- helloworld缓存 -->
    <cache name="HelloWorldCache"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="5"
           timeToLiveSeconds="5"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>

    <cache name="UserCache"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="1800"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>

</ehcache>

 

主启动类上:添加
@EnableCaching注解


配置文件:
spring:
  cache:
    ehcache:
#      指定缓存配置路径
      config: ehcache.xml
#      指定缓存类型
    type: ehcache  

 

diskStore : ehcache支持内存和磁盘两种存储

path :指定磁盘存储的位置
defaultCache : 默认的缓存

maxEntriesLocalHeap=“10000”
eternal=“false”
timeToIdleSeconds=“120”
timeToLiveSeconds=“120”
maxEntriesLocalDisk=“10000000”
diskExpiryThreadIntervalSeconds=“120”
memoryStoreEvictionPolicy=“LRU”
cache :自定的缓存,当自定的配置不满足实际情况时可以通过自定义(可以包含多个cache节点)

name : 缓存的名称,可以通过指定名称获取指定的某个Cache对象

maxElementsInMemory :内存中允许存储的最大的元素个数,0代表无限个

clearOnFlush:内存数量最大时是否清除。

eternal :设置缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。根据存储数据的不同,例如一些静态不变的数据如省市区等可以设置为永不过时

timeToIdleSeconds : 设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。

timeToLiveSeconds :缓存数据的生存时间(TTL),也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。

overflowToDisk :内存不足时,是否启用磁盘缓存。

maxEntriesLocalDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。

maxElementsOnDisk:硬盘最大缓存个数。

diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。

diskPersistent:是否在VM重启时存储硬盘的缓存数据。默认值是false。

diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。

 

posted @ 2022-04-19 19:17  余生请多指教ANT  阅读(32)  评论(0)    收藏  举报