Spring Boot 揭秘與實戰(二) 數據緩存篇 - 快速入門


文章目錄

  1. 1. 聲明式緩存
  2. 2. Spring Boot默認集成CacheManager
  3. 3. 默認的 ConcurrenMapCacheManager
  4. 4. 實戰演練5. 擴展閱讀
    1. 4.1. Maven 依賴
    2. 4.2. 開啟緩存支持
    3. 4.3. 服務層
    4. 4.4. 控制層
    5. 4.5. 運行
    6. 4.6. 課后作業
  5. 6. 源代碼

為了提高性能,減少數據庫的壓力,使用緩存是非常好的手段之一。本文,講解 Spring Boot 如何集成緩存管理。

聲明式緩存

Spring 定義 CacheManager 和 Cache 接口用來統一不同的緩存技術。例如 JCache、 EhCache、 Hazelcast、 Guava、 Redis 等。在使用 Spring 集成 Cache 的時候,我們需要注冊實現的 CacheManager 的 Bean。

Spring Boot默認集成CacheManager

Spring Boot 為我們自動配置了多個 CacheManager 的實現。

Spring Boot 為我們自動配置了 JcacheCacheConfiguration、 EhCacheCacheConfiguration、HazelcastCacheConfiguration、GuavaCacheConfiguration、RedisCacheConfiguration、SimpleCacheConfiguration 等。

默認的 ConcurrenMapCacheManager

Spring 從 Spring3.1 開始基於 java.util.concurrent.ConcurrentHashMap 實現的緩存管理器。所以, Spring Boot 默認使用 ConcurrentMapCacheManager 作為緩存技術。

以下是我們不引入其他緩存依賴情況下,控制台打印的日志信息。

  1. Bean 'cacheManager' of type [class org.springframework.cache.concurrent.ConcurrentMapCacheManager]

實戰演練

Maven 依賴

首先,我們先創建一個 POM 文件。

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4.  
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>1.3.3.RELEASE</version>
  9. </parent>
  10.  
  11. <groupId>com.lianggzone.demo</groupId>
  12. <artifactId>springboot-action-cache</artifactId>
  13. <version>0.1</version>
  14. <packaging>jar</packaging>
  15. <name>springboot-action-cache</name>
  16.  
  17. <dependencies>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-web</artifactId>
  25. </dependency>
  26.  
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-cache</artifactId>
  30. </dependency>
  31. </dependencies>
  32. <build>
  33. <plugins>
  34. <plugin>
  35. <groupId>org.apache.maven.plugins</groupId>
  36. <artifactId>maven-compiler-plugin</artifactId>
  37. <configuration>
  38. <defaultLibBundleDir>lib</defaultLibBundleDir>
  39. <source>1.7</source>
  40. <target>1.7</target>
  41. <encoding>UTF-8</encoding>
  42. </configuration>
  43. </plugin>
  44. <plugin>
  45. <groupId>org.apache.maven.plugins</groupId>
  46. <artifactId>maven-resources-plugin</artifactId>
  47. <configuration>
  48. <encoding>UTF-8</encoding>
  49. <useDefaultDelimiters>false</useDefaultDelimiters>
  50. <escapeString>\</escapeString>
  51. <delimiters>
  52. <delimiter>${*}</delimiter>
  53. </delimiters>
  54. </configuration>
  55. </plugin>
  56. <plugin>
  57. <groupId>org.springframework.boot</groupId>
  58. <artifactId>spring-boot-maven-plugin</artifactId>
  59. </plugin>
  60. </plugins>
  61. </build>
  62. </project>

其中,最核心的是添加 spring-boot-starter-cache 依賴。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>

開啟緩存支持

在 Spring Boot 中使用 @EnableCaching 開啟緩存支持。

  1. @Configuration
  2. @EnableCaching
  3. public class CacheConfiguration {}

服務層

創建一個服務類

  1. @Service("concurrenmapcache.cacheService")
  2. public class CacheService {
  3.  
  4. }

首先,我們先來講解下 @Cacheable 注解。@Cacheable 在方法執行前 Spring 先查看緩存中是否有數據,如果有數據,則直接返回緩存數據;若沒有數據,調用方法並將方法返回值放進緩存。有兩個重要的值, value,返回的內容將存儲在 value 定義的緩存的名字對象中。key,如果不指定將使用默認的 KeyGenerator 生成。

我們在查詢方法上,添加 @Cacheable 注解,其中緩存名稱為 concurrenmapcache。

  1. @Cacheable(value = "concurrenmapcache")
  2. public long getByCache() {
  3. try {
  4. Thread.sleep(3 * 1000);
  5. } catch (InterruptedException e) {
  6. e.printStackTrace();
  7. }
  8. return new Timestamp(System.currentTimeMillis()).getTime();
  9. }

@CachePut 與 @Cacheable 類似,但是它無論什么情況,都會將方法的返回值放到緩存中, 主要用於數據新增和修改方法。

  1. @CachePut(value = "concurrenmapcache")
  2. public long save() {
  3. long timestamp = new Timestamp(System.currentTimeMillis()).getTime();
  4. System.out.println("進行緩存:" + timestamp);
  5. return timestamp;
  6. }

@CacheEvict 將一條或多條數據從緩存中刪除, 主要用於刪除方法,用來從緩存中移除相應數據。

  1. @CacheEvict(value = "concurrenmapcache")
  2. public void delete() {
  3. System.out.println("刪除緩存");
  4. }

控制層

為了展現效果,我們先定義一組簡單的 RESTful API 接口進行測試。

  1. @RestController("concurrenmapcache.cacheController")
  2. @RequestMapping(value = "/concurrenmapcache/cache")
  3. public class CacheController {
  4. @Autowired
  5. private CacheService cacheService;
  6.  
  7. /**
  8. * 查詢方法
  9. */
  10. @RequestMapping(value = "", method = RequestMethod.GET)
  11. public String getByCache() {
  12. Long startTime = System.currentTimeMillis();
  13. long timestamp = this.cacheService.getByCache();
  14. Long endTime = System.currentTimeMillis();
  15. System.out.println("耗時: " + (endTime - startTime));
  16. return timestamp+"";
  17. }
  18.  
  19. /**
  20. * 保存方法
  21. */
  22. @RequestMapping(value = "", method = RequestMethod.POST)
  23. public void save() {
  24. this.cacheService.save();
  25. }
  26.  
  27. /**
  28. * 刪除方法
  29. */
  30. @RequestMapping(value = "", method = RequestMethod.DELETE)
  31. public void delete() {
  32. this.cacheService.delete();
  33. }
  34. }

運行

  1. @RestController
  2. @EnableAutoConfiguration
  3. @ComponentScan(basePackages = { "com.lianggzone.springboot" })
  4. public class WebMain {
  5.  
  6. public static void main(String[] args) throws Exception {
  7. SpringApplication.run(WebMain.class, args);
  8. }
  9. }

課后作業

我們分為幾個場景進行測試。

  • 多次調用查詢接口,查看緩存信息是否變化,控制台日志是否如下?你得到的結論是什么?
  • 調用保存接口,再調用查詢接口,查看緩存信息是否變化?你得到的結論是什么?
  • 調用刪除接口,再調用查詢接口,接口響應是否變慢了?你再看看控制台日志,你得到的結論是什么?

擴展閱讀

如果想更深入理解 Spring 的 Cache 機制,這邊推薦兩篇不錯的文章。

源代碼

相關示例完整代碼: springboot-action

(完)

 

微信公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM