三步搞定Spring Boot 缓存

本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能。在Spring Boot应用程序中,我们可以通过Spring Caching来快速搞定数据缓存。接下来我们将介绍如何在三步之内搞定Spring Boot缓存。

1. 创建一个Spring Boot工程并添加Maven依赖

你所创建的Spring Boot应用程序的maven依赖文件至少应该是下面的样子:

 
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  4. <modelVersion>4.0.0</modelVersion>

  5. <parent>

  6. <groupId>org.springframework.boot</groupId>

  7. <artifactId>spring-boot-starter-parent</artifactId>

  8. <version>2.1.3.RELEASE</version>

  9. <relativePath/> <!-- lookup parent from repository -->

  10. </parent>

  11. <groupId>com.ramostear</groupId>

  12. <artifactId>cache</artifactId>

  13. <version>0.0.1-SNAPSHOT</version>

  14. <name>cache</name>

  15. <description>Demo project for Spring Boot</description>

  16.  

  17. <properties>

  18. <java.version>1.8</java.version>

  19. </properties>

  20.  

  21. <dependencies>

  22. <dependency>

  23. <groupId>org.springframework.boot</groupId>

  24. <artifactId>spring-boot-starter-cache</artifactId>

  25. </dependency>

  26. <dependency>

  27. <groupId>org.springframework.boot</groupId>

  28. <artifactId>spring-boot-starter-web</artifactId>

  29. </dependency>

  30. <dependency>

  31. <groupId>org.ehcache</groupId>

  32. <artifactId>ehcache</artifactId>

  33. </dependency>

  34. <dependency>

  35. <groupId>javax.cache</groupId>

  36. <artifactId>cache-api</artifactId>

  37. </dependency>

  38. <dependency>

  39. <groupId>org.springframework.boot</groupId>

  40. <artifactId>spring-boot-starter-test</artifactId>

  41. <scope>test</scope>

  42. </dependency>

  43. <dependency>

  44. <groupId>org.projectlombok</groupId>

  45. <artifactId>lombok</artifactId>

  46. </dependency>

  47. </dependencies>

  48.  

  49. <build>

  50. <plugins>

  51. <plugin>

  52. <groupId>org.springframework.boot</groupId>

  53. <artifactId>spring-boot-maven-plugin</artifactId>

  54. </plugin>

  55. </plugins>

  56. </build>

  57.  

  58. </project>

依赖说明:

  • spring-boot-starter-cache为Spring Boot应用程序提供缓存支持

  • ehcache提供了Ehcache的缓存实现

  • cache-api 提供了基于JSR-107的缓存规范

2. 配置Ehcache缓存

现在,需要告诉Spring Boot去哪里找缓存配置文件,这需要在Spring Boot配置文件中进行设置:

 
  1. spring.cache.jcache.config=classpath:ehcache.xml

然后使用@EnableCaching注解开启Spring Boot应用程序缓存功能,你可以在应用主类中进行操作:

 
  1. package com.ramostear.cache;

  2.  

  3. import org.springframework.boot.SpringApplication;

  4. import org.springframework.boot.autoconfigure.SpringBootApplication;

  5. import org.springframework.cache.annotation.EnableCaching;

  6.  

  7. @SpringBootApplication

  8. @EnableCaching

  9. public class CacheApplication {

  10.  

  11. public static void main(String[] args) {

  12. SpringApplication.run(CacheApplication.class, args);

  13. }

  14. }

接下来,需要创建一个ehcache的配置文件,该文件放置在类路径下,如resources目录下:

 
  1. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  2. xmlns="http://www.ehcache.org/v3"

  3. xmlns:jsr107="http://www.ehcache.org/v3/jsr107"

  4. xsi:schemaLocation="

  5. http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd

  6. http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

  7. <service>

  8. <jsr107:defaults enable-statistics="true"/>

  9. </service>

  10.  

  11. <cache alias="person">

  12. <key-type>java.lang.Long</key-type>

  13. <value-type>com.ramostear.cache.entity.Person</value-type>

  14. <expiry>

  15. <ttl unit="minutes">1</ttl>

  16. </expiry>

  17. <listeners>

  18. <listener>

  19. <class>com.ramostear.cache.config.PersonCacheEventLogger</class>

  20. <event-firing-mode>ASYNCHRONOUS</event-firing-mode>

  21. <event-ordering-mode>UNORDERED</event-ordering-mode>

  22. <events-to-fire-on>CREATED</events-to-fire-on>

  23. <events-to-fire-on>UPDATED</events-to-fire-on>

  24. <events-to-fire-on>EXPIRED</events-to-fire-on>

  25. <events-to-fire-on>REMOVED</events-to-fire-on>

  26. <events-to-fire-on>EVICTED</events-to-fire-on>

  27. </listener>

  28. </listeners>

  29. <resources>

  30. <heap unit="entries">2000</heap>

  31. <offheap unit="MB">100</offheap>

  32. </resources>

  33. </cache>

  34. </config>

最后,还需要定义个缓存事件监听器,用于记录系统操作缓存数据的情况,最快的方法是实现CacheEventListener接口:

 
  1. package com.ramostear.cache.config;

  2.  

  3. import org.ehcache.event.CacheEvent;

  4. import org.ehcache.event.CacheEventListener;

  5. import org.slf4j.Logger;

  6. import org.slf4j.LoggerFactory;

  7.  

  8. /**

  9. * @author ramostear

  10. * @create-time 2019/4/7 0007-0:48

  11. * @modify by :

  12. * @since:

  13. */

  14. public class PersonCacheEventLogger implements CacheEventListener<Object,Object>{

  15.  

  16. private static final Logger logger = LoggerFactory.getLogger(PersonCacheEventLogger.class);

  17.  

  18. @Override

  19. public void onEvent(CacheEvent cacheEvent) {

  20. logger.info("person caching event {} {} {} {}",

  21. cacheEvent.getType(),

  22. cacheEvent.getKey(),

  23. cacheEvent.getOldValue(),

  24. cacheEvent.getNewValue());

  25. }

  26. }

3. 使用@Cacheable注解对方法进行注释

要让Spring Boot能够缓存我们的数据,还需要使用@Cacheable注解对业务方法进行注释,告诉Spring Boot该方法中产生的数据需要加入到缓存中:

 
  1. package com.ramostear.cache.service;

  2.  

  3. import com.ramostear.cache.entity.Person;

  4. import org.springframework.cache.annotation.Cacheable;

  5. import org.springframework.stereotype.Service;

  6.  

  7. /**

  8. * @author ramostear

  9. * @create-time 2019/4/7 0007-0:51

  10. * @modify by :

  11. * @since:

  12. */

  13. @Service(value = "personService")

  14. public class PersonService {

  15.  

  16. @Cacheable(cacheNames = "person",key = "#id")

  17. public Person getPerson(Long id){

  18. Person person = new Person(id,"ramostear","ramostear@163.com");

  19. return person;

  20. }

  21. }

通过以上三个步骤,我们就完成了Spring Boot的缓存功能。接下来,我们将测试一下缓存的实际情况。

4. 缓存测试

为了测试我们的应用程序,创建一个简单的Restful端点,它将调用PersonService返回一个Person对象:

 
  1. package com.ramostear.cache.controller;

  2.  

  3. import com.ramostear.cache.entity.Person;

  4. import com.ramostear.cache.service.PersonService;

  5. import org.springframework.beans.factory.annotation.Autowired;

  6. import org.springframework.http.HttpStatus;

  7. import org.springframework.http.ResponseEntity;

  8. import org.springframework.web.bind.annotation.GetMapping;

  9. import org.springframework.web.bind.annotation.PathVariable;

  10. import org.springframework.web.bind.annotation.RequestMapping;

  11. import org.springframework.web.bind.annotation.RestController;

  12.  

  13.  

  14. /**

  15. * @author ramostear

  16. * @create-time 2019/4/7 0007-0:54

  17. * @modify by :

  18. * @since:

  19. */

  20. @RestController

  21. @RequestMapping("/persons")

  22. public class PersonController {

  23.  

  24. @Autowired

  25. private PersonService personService;

  26.  

  27. @GetMapping("/{id}")

  28. public ResponseEntity<Person> person(@PathVariable(value = "id") Long id){

  29. return new ResponseEntity<>(personService.getPerson(id), HttpStatus.OK);

  30. }

  31. }

Person是一个简单的POJO类:

 
  1. package com.ramostear.cache.entity;

  2.  

  3.  

  4. import lombok.AllArgsConstructor;

  5. import lombok.Getter;

  6. import lombok.NoArgsConstructor;

  7. import lombok.Setter;

  8.  

  9. import java.io.Serializable;

  10.  

  11. /**

  12. * @author ramostear

  13. * @create-time 2019/4/7 0007-0:45

  14. * @modify by :

  15. * @since:

  16. */

  17. @Getter

  18. @Setter

  19. @AllArgsConstructor

  20. @NoArgsConstructor

  21. public class Person implements Serializable{

  22.  

  23. private Long id;

  24.  

  25. private String username;

  26.  

  27. private String email;

  28. }

以上准备工作都完成后,让我们编译并运行应用程序。项目成功启动后,使用浏览器打开:http://localhost:8080/persons/1 ,你将在浏览器页面中看到如下的信息:

 
  1. {"id":1,"username":"ramostear","email":"ramostear@163.com"}

此时在观察控制台输出的日志信息:

 
  1. 2019-04-07 01:08:01.001 INFO 6704 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms

  2. 2019-04-07 01:08:01.054 INFO 6704 --- [e [_default_]-0] c.r.cache.config.PersonCacheEventLogger : person caching event CREATED 1 null com.ramostear.cache.entity.Person@ba8a729

由于我们是第一次请求API,没有任何缓存数据。因此,Ehcache创建了一条缓存数据,可以通过CREATED看一了解到。

我们在ehcache.xml文件中将缓存过期时间设置成了1分钟(1),因此在一分钟之内我们刷新浏览器,不会看到有新的日志输出,一分钟之后,缓存过期,我们再次刷新浏览器,将看到如下的日志输出:

 
  1. 2019-04-07 01:09:28.612 INFO 6704 --- [e [_default_]-1] c.r.cache.config.PersonCacheEventLogger : person caching event EXPIRED 1 com.ramostear.cache.entity.Person@a9f3c57 null

  2. 2019-04-07 01:09:28.612 INFO 6704 --- [e [_default_]-1] c.r.cache.config.PersonCacheEventLogger : person caching event CREATED 1 null com.ramostear.cache.entity.Person@416900ce

第一条日志提示缓存已经过期,第二条日志提示Ehcache重新创建了一条缓存数据。

结束语

在本次案例中,通过简单的三个步骤,讲解了基于Ehcache的Spring Boot应用程序缓存实现。文章内容重在缓存实现的基本步骤与方法,简化了具体的业务代码,有兴趣的朋友可以自行扩展,期间遇到问题也可以随时与我联系。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值