Spring Boot 揭秘与实战(二) 数据缓存篇 - EhCache

时间:2023-03-08 23:54:09
Spring Boot 揭秘与实战(二) 数据缓存篇 - EhCache

本文,讲解 Spring Boot 如何集成 EhCache,实现缓存。

在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门」后,对 Spring Boot 集成缓存机制有一定了解后,我们来了解下 EhCache 的使用。

EhCache 集成

EhCache 是一个纯 Java 的进程内缓存框架,具有快速、精干等特点,是 Hibernate 中默认的 CacheProvider。

在 Spring Boot 中集成 EhCache 非常容易,只需要两个步骤。

首先,在 pom.xml 中增加 EhCache 依赖。

  1. <dependency>
  2. <groupId>net.sf.ehcache</groupId>
  3. <artifactId>ehcache</artifactId>
  4. </dependency>

第二步,在 src/main/resources 目录下创建 ehcache.xml。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="ehcache.xsd">
  4. <cache name="ehcache"
  5. maxElementsInMemory="1000"
  6. timeToLiveSeconds="300">
  7. </cache>
  8. </ehcache>

其中,maxElementsInMemory,表示缓存最大数目。 timeToLiveSeconds: ,表示设置对象在失效前允许存活时间(单位:秒)。

如果想对 ehcache.xml 更深入的了解,可以参考 http://www.ehcache.org/ehcache.xml。

运行起来,控制台打印的日志信息,说明已经是EhCacheManager实例,说明 EhCache 开启成功了。

  1. Bean 'cacheManager' of type [class org.springframework.cache.ehcache.EhCacheCacheManager]

源代码

相关示例完整代码: springboot-action

(完)

如果觉得我的文章对你有帮助,请随意打赏。

Spring Boot 揭秘与实战(二) 数据缓存篇 - EhCache