# 1.EhCache

## 一、 添加依赖

```markup
<!-- caching -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
```

## 二、 配置文件：

```
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:config/ehcache.xml
```

ehcache.xml

```markup
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">

    <cache name="demoCache"
           eternal="false"
           maxEntriesLocalHeap="0"
           timeToIdleSeconds="200"></cache>

    <!-- eternal：true表示对象永不过期，此时会忽略timeToIdleSeconds和timeToLiveSeconds属性，默认为false -->
    <!-- maxEntriesLocalHeap：堆内存中最大缓存对象数，0没有限制 -->
    <!-- timeToIdleSeconds： 设定允许对象处于空闲状态的最长时间，以秒为单位。当对象自从最近一次被访问后，如果处于空闲状态的时间超过了timeToIdleSeconds属性值，这个对象就会过期，EHCache将把它从缓存中清空。只有当eternal属性为false，该属性才有效。如果该属性值为0，则表示对象可以无限期地处于空闲状态 -->
</ehcache>
```

> 配置信息介绍
>
> ```markup
> <?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">
>     <diskStore path="java.io.tmpdir/Tmp_EhCache" />
>
>     <!-- 默认配置 -->
>     <defaultCache maxElementsInMemory="5000" eternal="false"
>         timeToIdleSeconds="120" timeToLiveSeconds="120"
>         memoryStoreEvictionPolicy="LRU" overflowToDisk="false" />
>
>     <cache name="baseCache" maxElementsInMemory="10000"
>         maxElementsOnDisk="100000" />
>
> </ehcache>
> ```
>
> ```java
> name:缓存名称。  
> maxElementsInMemory：缓存最大个数。  
> eternal:对象是否永久有效，一但设置了，timeout将不起作用。  
> timeToIdleSeconds：设置对象在失效前的允许闲置时间（单位：秒）。仅当eternal=false对象不是永久有效时使用，可选属性，默认值是0，也就是可闲置时间无穷大。  
> timeToLiveSeconds：设置对象在失效前允许存活时间（单位：秒）。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用，默认是0.，也就是对象存活时间无穷大。  
> overflowToDisk：当内存中对象数量达到maxElementsInMemory时，Ehcache将会对象写到磁盘中。  
> diskSpoolBufferSizeMB：这个参数设置DiskStore（磁盘缓存）的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。  
> maxElementsOnDisk：硬盘最大缓存个数。  
> 1diskPersistent：是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.  
> 1diskExpiryThreadIntervalSeconds：磁盘失效线程运行时间间隔，默认是120秒。  
> 1memoryStoreEvictionPolicy：当达到maxElementsInMemory限制时，Ehcache将会根据指定的策略去清理内存。默认策略是LRU（最近最少使用）。你可以设置为FIFO（先进先出）或是LFU（较少使用）。  
> 1clearOnFlush：内存数量最大时是否清除。
> ```

## 三、 启用注解支持：

```java
@EnableCaching：启用缓存注解
```

添加在main方法上面

具体代码实现

![](https://3562539340-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LfnT314x6hQ7gJbPKxx%2F-LfnTB6gvTwJcyb-RbKo%2F-LfnTILDSXrOQSAfQwzB%2F1.1.png?generation=1558862969228901\&alt=media)

cache/DemoUserLogCache.java 接口

```java
package com.shuju.test2.cache;


import com.shuju.test2.bean.DemoUserLog;

public interface DemoUserLogCache {

    /**
     * 查询
     *
     * @param id
     * @return
     */
    DemoUserLog selectById(Integer id);

    /**
     * 更新
     *
     * @param roncooUserLog
     * @return
     */
    DemoUserLog updateById(DemoUserLog roncooUserLog);

    /**
     * 删除
     *
     * @param id
     * @return
     */
    String deleteById(Integer id);
}
```

cache/impl/DemoUserLogCacheImpl.java

```java
package com.shuju.test2.cache.impl;

import com.shuju.test2.bean.DemoUserLog;
import com.shuju.test2.cache.DemoUserLogCache;
import com.shuju.test2.dao.DemoUserLogDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@CacheConfig(cacheNames = "demoCache")
@Repository
public class DemoUserLogCacheImpl implements DemoUserLogCache {

    @Autowired
    private DemoUserLogDao demoUserLogDao;

    @Cacheable(key = "#p0")
    @Override
    public DemoUserLog selectById(Integer id) {
        System.out.println("查询功能，缓存找不到，直接读库, id=" + id);
        return demoUserLogDao.findById(id).get();
    }

    @CachePut(key = "#p0")
    @Override
    public DemoUserLog updateById(DemoUserLog demoUserLog) {
        System.out.println("更新功能，更新缓存，直接写库, id=" + demoUserLog);
        return demoUserLogDao.save(demoUserLog);
    }

    @CacheEvict(key = "#p0")
    @Override
    public String deleteById(Integer id) {
        System.out.println("删除功能，删除缓存，直接写库, id=" + id);
        return "清空缓存成功";
    }
}
```

注解说明：

* @CacheConfig：缓存配置
* @Cacheable：应用到读取数据的方法上，即可缓存的方法，如查找方法：先从缓存中读取，如果没有再调 用方法获取数据，然后把数据添加到缓存中。**适用于查找**
* @CachePut：主要针对方法配置，能够根据方法的请求参数对其结果进行缓存，和 @Cacheable 不同的是，它每次都会触发真实方法的调用。**适用于更新和插入**
* @CacheEvict：主要针对方法配置，能够根据一定的条件对缓存进行清空。**适用于删除**&#x20;

创建用于测试的controller/ApiController.java

```java
package com.shuju.test2.controller;

import java.util.Date;
import java.util.HashMap;

import com.shuju.test2.bean.DemoUserLog;
import com.shuju.test2.cache.DemoUserLogCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private DemoUserLogCache demoUserLogCache;

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    public DemoUserLog get(@RequestParam(defaultValue = "1") Integer id) {
        return demoUserLogCache.selectById(id);
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public DemoUserLog update(@RequestParam(defaultValue = "1") Integer id) {
        DemoUserLog bean = demoUserLogCache.selectById(id);
        bean.setUserName("测试");
        bean.setCreateTime(new Date());
        demoUserLogCache.updateById(bean);
        return bean;
    }

    @RequestMapping(value = "/del", method = RequestMethod.GET)
    public String del(@RequestParam(defaultValue = "1") Integer id) {
        return demoUserLogCache.deleteById(id);
    }
}
```

## 资料

[spring boot学习(十三)SpringBoot缓存(EhCache 2.x 篇)](https://blog.csdn.net/u011244202/article/details/55667868)

手动清除缓存

```java
@Autowired
private CacheManager cacheManager;
@RequestMapping("/remoKey")
public void remoKey() {
    cacheManager.getCache("cachename").clear();
}
```
