Spring Boot 2 缓存注解 缓存工具类 缓存切换

1.配置文件

application.yml

server:
  port: 8899
  servlet:
    context-path: /

spring:
  profiles:
    active: dev
  cache:
    type: ehcache #ehcache caffeine redis
    ehcache:
      config: classpath:ehcache.xml
    cache-names: testName,captchaCache  #ehcache时cacheName由ehcache.xml定义
    caffeine:
      spec: maximumSize=500,expireAfterAccess=600s
  redis:
    host: 127.0.0.1
    port: 6379
    password:

 

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>

    <!--
      
        缓存配置
           diskStore:指定数据在磁盘中的存储位置。
           name:缓存名称。
           defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略,以下属性是必须的:
           maxElementsInMemory:缓存最大个数。
           eternal:对象是否永久有效,一但设置了,timeout将不起作用。
           timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
           timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
           overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
           diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
           maxElementsOnDisk:硬盘最大缓存个数。
           diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
           diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
           memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
           clearOnFlush:内存数量最大时是否清除。
    -->
    <diskStore path="e:\ehcache" />
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
    />
    <cache
            name="captchaCache"
            eternal="false"
            maxElementsInMemory="100"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="600"
            memoryStoreEvictionPolicy="LRU" />

</ehcache>

2.缓存工具类 CacheUtil

package cn.flyinke.sb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import static javafx.scene.input.KeyCode.T;

/**
 * @author flyinke
 * @time 2018/12/21
 * @description
 */
@Component
public class CacheUitl {

    @Autowired
    private CacheManager cacheManager;

    private static CacheManager cm;

    @PostConstruct
    public void init(){
        cm = cacheManager;
    }

    public static void put(String cacheName,String key,Object value){
        Cache cache = cm.getCache(cacheName);
        cache.put(key,value);
    }

    public static Object get(String cacheName,String key){
        Cache cache = cm.getCache(cacheName);
        if(cache == null){
            return null;
        }
        return cache.get(key).get();
    }

    public static <T> T get(String cacheName,String key,Class<T> clazz) {
        Cache cache = cm.getCache(cacheName);
        return cache.get(key, clazz);
    }

    public static void evict(String cacheName,String key){
        Cache cache = cm.getCache(cacheName);
        cache.evict(key);
    }
}

3.测试

IndexService

package cn.flyinke.sb;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author flyinke
 * @time 2018/12/21
 * @description
 */
@Service
public class IndexService {

    @Cacheable(cacheNames = "captchaCache",key = "#p")
    public double random(String p){
        return Math.random();
    }
}

IndexController

package cn.flyinke.sb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

/**
 * @author flyinke
 * @time 2018/12/20
 * @description
 */
@RestController
@RequestMapping("/api")
public class IndexController {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private IndexService indexService;

    @RequestMapping("/index")
    public Object index(){

        return "index";
    }

    @RequestMapping("/cache")
    public Object cache(){
        System.out.println("cacheNames:"+cacheManager.getCacheNames());
        Cache cache = cacheManager.getCache("captchaCache");
        cache.put("key-1","value-1");
        System.out.println("cache:key-1="+cache.get("key-1",String.class));
        System.out.println("cacheNames:"+cacheManager.getCacheNames());
        return cacheManager.getCacheNames();
    }

    @RequestMapping("/cache2")
    public Object cache2(){
        CacheUitl.get("captchaCache","aaaaa",String.class);
        Map map = new HashMap<>();
        map.put("name","Tom");
        map.put("age",19);
        CacheUitl.put("captchaCache","key-2",map);

        Map re = (Map) CacheUitl.get("captchaCache","key-2");
        return re;
    }
    @RequestMapping("/cache3")
    public Object cache3(@RequestParam String p){
        return indexService.random(p);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值