# spring-boot-demo-cache-ehcache
> 此 demo 主要演示了 Spring Boot 如何集成 ehcache 使用缓存。
## pom.xml
```xml
* 启动类 *
* * @package: com.xkcoding.cache.ehcache * @description: 启动类 * @author: yangkai.shen * @date: Created in 2018/11/16 17:02 * @copyright: Copyright (c) 2018 * @version: V1.0 * @modified: yangkai.shen */ @SpringBootApplication @EnableCaching public class SpringBootDemoCacheEhcacheApplication { public static void main(String[] args) { SpringApplication.run(SpringBootDemoCacheEhcacheApplication.class, args); } } ``` ## application.yml ```yaml spring: cache: type: ehcache ehcache: config: classpath:ehcache.xml logging: level: com.xkcoding: debug ``` ## ehcache.xml ```xml* UserService *
* * @package: com.xkcoding.cache.ehcache.service.impl * @description: UserService * @author: yangkai.shen * @date: Created in 2018/11/16 16:54 * @copyright: Copyright (c) 2018 * @version: V1.0 * @modified: yangkai.shen */ @Service @Slf4j public class UserServiceImpl implements UserService { /** * 模拟数据库 */ private static final Map* ehcache缓存测试 *
* * @package: com.xkcoding.cache.ehcache.service * @description: ehcache缓存测试 * @author: yangkai.shen * @date: Created in 2018/11/16 16:58 * @copyright: Copyright (c) 2018 * @version: V1.0 * @modified: yangkai.shen */ @Slf4j public class UserServiceTest extends SpringBootDemoCacheEhcacheApplicationTests { @Autowired private UserService userService; /** * 获取两次,查看日志验证缓存 */ @Test public void getTwice() { // 模拟查询id为1的用户 User user1 = userService.get(1L); log.debug("【user1】= {}", user1); // 再次查询 User user2 = userService.get(1L); log.debug("【user2】= {}", user2); // 查看日志,只打印一次日志,证明缓存生效 } /** * 先存,再查询,查看日志验证缓存 */ @Test public void getAfterSave() { userService.saveOrUpdate(new User(4L, "user4")); User user = userService.get(4L); log.debug("【user】= {}", user); // 查看日志,只打印保存用户的日志,查询是未触发查询日志,因此缓存生效 } /** * 测试删除,查看redis是否存在缓存数据 */ @Test public void deleteUser() { // 查询一次,使ehcache中存在缓存数据 userService.get(1L); // 删除,查看ehcache是否存在缓存数据 userService.delete(1L); } } ``` ## 参考 - Ehcache 官网:http://www.ehcache.org/documentation/ - Spring Boot 官方文档:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-ehcache2 - 博客:https://juejin.im/post/5b308de9518825748b56ae1d