springboot-cache

           <!--开启 cache 缓存-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!-- ehcache 缓存 -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
启动类Application添加注解
    @EnableCaching

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">
    <!--默认临时缓存路径
    user.home – 用户主目录
    user.dir      – 用户当前工作目录
    java.io.tmpdir – 默认临时文件路径
    路径是:C:Users*****AppDataLocalTemp-->
    <diskStore path="java.io.tmpdir" />
    <defaultCache
            eternal="false"
            maxElementsInMemory="200"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="3600"
            memoryStoreEvictionPolicy="LRU" />  
    <cache
            name="users"
            eternal="true"
            maxElementsInMemory="100"
            overflowToDisk="true"
            diskPersistent="false"
            timeToIdleSeconds="0"
            timeToLiveSeconds="0"
            memoryStoreEvictionPolicy="LRU"
            diskSpoolBufferSizeMB="100"
            diskExpiryThreadIntervalSeconds="120"
            clearOnFlush="false"  />
</ehcache>

Cache实例获取

private Cache getCacheInstance(){
        //获取EhCacheCacheManager类
        EhCacheCacheManager cacheCacheManager= ApplicationContextUtils.applicationContext.getBean(EhCacheCacheManager.class);
        //获取CacheManager类
        net.sf.ehcache.CacheManager cacheManager=   cacheCacheManager.getCacheManager();
        //获取Cache
        Cache cache=   cacheManager.getCache("user");
        return cache;
    }

操作

cache.put( new Element(token,data) );
cache.remove(token);

Element e = cache.get(token);
if(e!=null){
Map<String,Object> m = (HashMap)(e.getObjectValue()) ;
}

注解存取

// 缓存名称-配置文件name
private
static final String CACHE_NAME = "users"; //#key 存储的key condition缓存的条件

@Cacheable(value = CACHE_NAME ,key = "#key",condition="#param1!= #param2")
@Override
public Object getDataByDate(String param1, String param2,String key) {
return XXXXXXXXXX;
}
原文地址:https://www.cnblogs.com/feecy/p/12924322.html