You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 7.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. # spring-boot-demo-cache-ehcache
  2. > 此 demo 主要演示了 Spring Boot 如何集成 ehcache 使用缓存。
  3. ## pom.xml
  4. ```xml
  5. <?xml version="1.0" encoding="UTF-8"?>
  6. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  8. <modelVersion>4.0.0</modelVersion>
  9. <artifactId>spring-boot-demo-cache-ehcache</artifactId>
  10. <version>1.0.0-SNAPSHOT</version>
  11. <packaging>jar</packaging>
  12. <name>spring-boot-demo-cache-ehcache</name>
  13. <description>Demo project for Spring Boot</description>
  14. <parent>
  15. <groupId>com.xkcoding</groupId>
  16. <artifactId>spring-boot-demo</artifactId>
  17. <version>1.0.0-SNAPSHOT</version>
  18. </parent>
  19. <properties>
  20. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  21. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  22. <java.version>1.8</java.version>
  23. </properties>
  24. <dependencies>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-cache</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>net.sf.ehcache</groupId>
  35. <artifactId>ehcache</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.projectlombok</groupId>
  39. <artifactId>lombok</artifactId>
  40. <optional>true</optional>
  41. </dependency>
  42. <dependency>
  43. <groupId>com.google.guava</groupId>
  44. <artifactId>guava</artifactId>
  45. </dependency>
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. </dependencies>
  52. <build>
  53. <finalName>spring-boot-demo-cache-ehcache</finalName>
  54. <plugins>
  55. <plugin>
  56. <groupId>org.springframework.boot</groupId>
  57. <artifactId>spring-boot-maven-plugin</artifactId>
  58. </plugin>
  59. </plugins>
  60. </build>
  61. </project>
  62. ```
  63. ## SpringBootDemoCacheEhcacheApplication.java
  64. ```java
  65. /**
  66. * <p>
  67. * 启动类
  68. * </p>
  69. *
  70. * @author yangkai.shen
  71. * @date Created in 2018-11-16 17:02
  72. */
  73. @SpringBootApplication
  74. @EnableCaching
  75. public class SpringBootDemoCacheEhcacheApplication {
  76. public static void main(String[] args) {
  77. SpringApplication.run(SpringBootDemoCacheEhcacheApplication.class, args);
  78. }
  79. }
  80. ```
  81. ## application.yml
  82. ```yaml
  83. spring:
  84. cache:
  85. type: ehcache
  86. ehcache:
  87. config: classpath:ehcache.xml
  88. logging:
  89. level:
  90. com.xkcoding: debug
  91. ```
  92. ## ehcache.xml
  93. ```xml
  94. <!-- ehcache配置 -->
  95. <ehcache
  96. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  97. xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
  98. updateCheck="false">
  99. <!--缓存路径,用户目录下的base_ehcache目录-->
  100. <diskStore path="user.home/base_ehcache"/>
  101. <defaultCache
  102. maxElementsInMemory="20000"
  103. eternal="false"
  104. timeToIdleSeconds="120"
  105. timeToLiveSeconds="120"
  106. overflowToDisk="true"
  107. maxElementsOnDisk="10000000"
  108. diskPersistent="false"
  109. diskExpiryThreadIntervalSeconds="120"
  110. memoryStoreEvictionPolicy="LRU"/>
  111. <!--
  112. 缓存文件名:user,同样的可以配置多个缓存
  113. maxElementsInMemory:内存中最多存储
  114. eternal:外部存储
  115. overflowToDisk:超出缓存到磁盘
  116. diskPersistent:磁盘持久化
  117. timeToLiveSeconds:缓存时间
  118. diskExpiryThreadIntervalSeconds:磁盘过期时间
  119. -->
  120. <cache name="user"
  121. maxElementsInMemory="20000"
  122. eternal="true"
  123. overflowToDisk="true"
  124. diskPersistent="false"
  125. timeToLiveSeconds="0"
  126. diskExpiryThreadIntervalSeconds="120"/>
  127. </ehcache>
  128. ```
  129. ## UserServiceImpl.java
  130. ```java
  131. /**
  132. * <p>
  133. * UserService
  134. * </p>
  135. *
  136. * @author yangkai.shen
  137. * @date Created in 2018-11-16 16:54
  138. */
  139. @Service
  140. @Slf4j
  141. public class UserServiceImpl implements UserService {
  142. /**
  143. * 模拟数据库
  144. */
  145. private static final Map<Long, User> DATABASES = Maps.newConcurrentMap();
  146. /**
  147. * 初始化数据
  148. */
  149. static {
  150. DATABASES.put(1L, new User(1L, "user1"));
  151. DATABASES.put(2L, new User(2L, "user2"));
  152. DATABASES.put(3L, new User(3L, "user3"));
  153. }
  154. /**
  155. * 保存或修改用户
  156. *
  157. * @param user 用户对象
  158. * @return 操作结果
  159. */
  160. @CachePut(value = "user", key = "#user.id")
  161. @Override
  162. public User saveOrUpdate(User user) {
  163. DATABASES.put(user.getId(), user);
  164. log.info("保存用户【user】= {}", user);
  165. return user;
  166. }
  167. /**
  168. * 获取用户
  169. *
  170. * @param id key值
  171. * @return 返回结果
  172. */
  173. @Cacheable(value = "user", key = "#id")
  174. @Override
  175. public User get(Long id) {
  176. // 我们假设从数据库读取
  177. log.info("查询用户【id】= {}", id);
  178. return DATABASES.get(id);
  179. }
  180. /**
  181. * 删除
  182. *
  183. * @param id key值
  184. */
  185. @CacheEvict(value = "user", key = "#id")
  186. @Override
  187. public void delete(Long id) {
  188. DATABASES.remove(id);
  189. log.info("删除用户【id】= {}", id);
  190. }
  191. }
  192. ```
  193. ## UserServiceTest.java
  194. ```java
  195. /**
  196. * <p>
  197. * ehcache缓存测试
  198. * </p>
  199. *
  200. * @author yangkai.shen
  201. * @date Created in 2018-11-16 16:58
  202. */
  203. @Slf4j
  204. public class UserServiceTest extends SpringBootDemoCacheEhcacheApplicationTests {
  205. @Autowired
  206. private UserService userService;
  207. /**
  208. * 获取两次,查看日志验证缓存
  209. */
  210. @Test
  211. public void getTwice() {
  212. // 模拟查询id为1的用户
  213. User user1 = userService.get(1L);
  214. log.debug("【user1】= {}", user1);
  215. // 再次查询
  216. User user2 = userService.get(1L);
  217. log.debug("【user2】= {}", user2);
  218. // 查看日志,只打印一次日志,证明缓存生效
  219. }
  220. /**
  221. * 先存,再查询,查看日志验证缓存
  222. */
  223. @Test
  224. public void getAfterSave() {
  225. userService.saveOrUpdate(new User(4L, "user4"));
  226. User user = userService.get(4L);
  227. log.debug("【user】= {}", user);
  228. // 查看日志,只打印保存用户的日志,查询是未触发查询日志,因此缓存生效
  229. }
  230. /**
  231. * 测试删除,查看redis是否存在缓存数据
  232. */
  233. @Test
  234. public void deleteUser() {
  235. // 查询一次,使ehcache中存在缓存数据
  236. userService.get(1L);
  237. // 删除,查看ehcache是否存在缓存数据
  238. userService.delete(1L);
  239. }
  240. }
  241. ```
  242. ## 参考
  243. - Ehcache 官网:http://www.ehcache.org/documentation/
  244. - Spring Boot 官方文档:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#boot-features-caching-provider-ehcache2
  245. - 博客:https://juejin.im/post/5b308de9518825748b56ae1d