<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                # Spring Boot 緩存示例教程 > 原文: [https://howtodoinjava.com/spring-boot2/spring-boot-cache-example/](https://howtodoinjava.com/spring-boot2/spring-boot-cache-example/) 在本[ Spring Boot 教程](https://howtodoinjava.com/spring-boot-tutorials/)中,從 Spring 框架緩存支持中學習輕松管理應用程序**緩存**。 Spring 在緩存切面具有一些不錯的功能, **spring cache API** 上的抽象非常易于使用。 ## 1\. 什么是緩存? 緩存是一種增強系統性能的機制。 它是位于應用程序和持久數據庫之間的臨時內存。 高速緩存存儲器存儲最近使用的數據項,以盡可能減少數據庫命中的次數。 #### 1.1. 為什么我們需要緩存? 緩存應用程序中經常使用的數據是提高應用程序性能的一種非常流行的技術。 通過緩存,我們將此類經常訪問的數據存儲在內存中,以避免每次用戶請求數據時都訪問昂貴的后端。 與從數據庫,文件系統或其他服務調用中獲取數據相比,從內存中進行數據訪問總是更快。 #### 1.2. 應該緩存什么數據? 這主要是關于應該駐留在緩存中并經過緩存生命周期的數據類型的決定。 在不同的情況下以及對我們可以容忍過時的數據的要求切面,它會有所不同。 因此,每個項目的緩存候選者將有所不同,但仍然只是緩存的少數幾個示例: * 電子商務商店中可用的產品列表 * 任何不經常更改的主數據 * 任何經常使用的數據庫讀取查詢,其中至少在特定時間段內,每個調用中的結果都不會更改。 ## 2\. 緩存類型 通常,可以看到以下類型的緩存。 #### 2.1. 內存中緩存 這是最常使用的區域,在該區域廣泛使用緩存來提高應用程序的性能。 內存緩存(例如 Memcached 和 Radis)是應用程序和數據存儲之間的鍵值存儲。 由于數據保存在 RAM 中,因此它比將數據存儲在磁盤上的典型數據庫快得多。 RAM 比磁盤更受限制,因此高速緩存失效算法(例如**最近最少使用(LRU)**)可以幫助使“冷”條目失效并將“熱”數據保留在 RAM 中。 `Memcached`是一種內存緩存,其中`Redis`更高級,它允許我們備份和還原功能,它是分布式緩存工具,可以管理分布式集群中的緩存。 #### 2.2. 數據庫緩存 您的數據庫通常在默認配置中包括某種程度的緩存,這些緩存針對通用用例進行了優化。 針對特定的使用模式調整這些設置可以進一步提高性能。 在該領域流行的是`Hibernate`或任何 ORM 框架的一級緩存。 #### 2.3. Web 服務器緩存 反向代理和緩存(例如 [Varnish](https://varnish-cache.org/index.html))可以直接提供靜態和動態內容。 Web 服務器還可以緩存請求,返回響應而無需聯系應用程序服務器。 在當今的 API 時代,如果我們想在網絡服務器級別緩存 API 響應,則此選項是可行的。 #### 2.4. CDN 緩存 緩存可以位于客戶端(操作系統或瀏覽器),服務器端或不同的緩存層中。 ## 3\. Spring Boot 緩存注解 Spring 框架為不同的緩存提供程序提供**緩存抽象 api** 。 API 的用法非常簡單,但功能非常強大。 今天,我們將在緩存中看到基于注解的 Java 配置。 注意,我們也可以通過 XML 配置實現類似的功能。 #### 3.1. `@EnableCaching` 它啟用了 Spring 的注解驅動的緩存管理功能。 在 spring boot 項目中,我們需要將其添加到帶有`@SpringBootApplication`注解的啟動應用程序類中。 Spring 提供了一個并發哈希圖作為默認緩存,但是我們可以重寫`CacheManager`來輕松注冊外部緩存提供程序。 #### 3.2. `@Cacheable` 它在方法級別上用于使 spring 知道該方法的響應是可緩存的。 Spring 管理此方法對注解屬性中指定的緩存的請求/響應。 例如,`@Cacheable ("cache-name1", “cache-name2”)`。 `@Cacheable`注解具有更多選項。 就像我們可以從方法的請求中指定緩存的鍵一樣。 如果未指定任何內容,spring 將使用所有類字段并將其用作緩存鍵(主要是`HashCode`)來維護緩存,但是我們可以通過提供鍵信息來覆蓋此行為。 ```java @Cacheable(value="books", key="#isbn") public Book findStoryBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) @Cacheable(value="books", key="#isbn.rawNumber") public Book findStoryBook (ISBN isbn, boolean checkWarehouse, boolean includeUsed) @Cacheable(value="books", key="T(classType).hash(#isbn)") public Book findStoryBook (ISBN isbn, boolean checkWarehouse, boolean includeUsed) ``` 我們也可以使用**條件緩存**。 例如, ```java @Cacheable(value="book", condition="#name.length < 50") public Book findStoryBook (String name) ``` #### 3.3. `@CachePut` 有時我們需要手動操作緩存,以在方法調用之前放置(更新)緩存。 這將允許我們更新緩存,也將允許執行該方法。 該方法將始終執行,并將其結果放入緩存(根據`@CachePut`選項)。 它支持與`@Cacheable`相同的選項,應該用于緩存填充,而不是方法流程優化。 請注意,一般不建議在同一方法上使用`@CachePut`和`注解批注,因為它們的行為不同。 后者導致通過使用緩存跳過方法執行,而前者則強制執行以便執行緩存更新。 這會導致意外的行為,并且除了特定的極端情況(例如具有相互排斥條件的注解)外,應避免此類聲明。 #### 3.4. `@CacheEvict` 當我們需要移出(刪除)先前加載的主數據的緩存時使用它。 當將執行`CacheEvict`注解的方法時,它將清除緩存。 我們可以在此處指定鍵以刪除緩存,如果需要刪除緩存的所有條目,則需要使用`allEntries=true`。 當需要清除整個緩存區域時,此選項非常有用 – 而不是逐出每個條目(由于效率低下,這將需要很長時間),所有條目都將在一次操作中被刪除。 #### 3.5. `@Cache` 當我們同時需要`CachePut`和`CacheEvict`時,需要此注解。 ## 4\. 如何在 Spring Boot 中注冊緩存引擎 Spring Boot 提供了與以下緩存提供程序的集成。 如果在類路徑中存在默認選項,并且我們已通過 Spring Boot 應用程序中的`@EnableCaching`啟用了緩存,則 Spring Boot 會使用默認選項進行自動配置。 * JCache(JSR-107)(EhCache 3,Hazelcast,Infinispan 等) * EhCache 2.x * Hazelcast * Infinispan * Couchbase * RedisC * Caffeine * SimpleCache 我們可以通過覆蓋特定于緩存提供程序的設置來覆蓋 Spring 運行中的特定緩存行為,例如: ```java spring.cache.infinispan.config=infinispan.xml ``` 有關詳細信息,我們可以在此處查看[官方的 Spring Boot 文檔](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html)。 ## 5\. Spring Boot 緩存示例 在此 **spring boot cahce 配置示例**中,我們將看到如何在 spring boot 中啟用默認緩存,并為一種業務方法啟用緩存。 最后,我們將在重復調用相同方法的情況下測試應用程序性能。 我們將使用`Thread.sleep()`方法來模擬實際方法調用中的延遲,以感受緩存的效果。 因此,讓我們遵循創建項目和測試的簡單步驟。 #### 5.1 創建 Spring Boot 項目 創建一個名為`spring-cache`且具有`spring-boot-web`依賴關系的簡單 Spring Boot 項目,以將其托管在 Web 服務器中。 為此,我們需要轉到 https://start.spring.io/ 并提供 Maven 坐標并選擇依賴項。 下載包含框架項目的 zip 文件。 然后,一旦解壓縮到合適的文件夾中,我們就需要將其導入 eclipse 中。 進行初始 mvn 全新安裝,以將所有必需的依賴項下載到本地存儲庫。 ![Spring Boot Project Creation](https://img.kancloud.cn/4e/1c/4e1ca2f09e910cde2d2e51a962e47b43_1361x700.jpg) Spring Boot 項目創建 #### 5.2 創建 HTTP GET REST API 使用 GET 請求創建一個 REST 服務,它將成為搜索服務。 我們的主要目標是將方法的響應緩存在服務層中,在此我們將引入一個故意的延遲來模擬實際的后端服務調用以獲取結果。 在第一個匹配中,響應將被延遲,因為我們在應用程序中會有一些模擬的延遲,但是在隨后的調用中,我們將獲得更快的響應。 `Student.java` ```java package com.example.springcache.domain; public class Student { String id; String name; String clz; public Student(String id, String name, String clz) { super(); this.id = id; this.name = name; this.clz = clz; } //Setters and getters } ``` `StudentService.java` ```java package com.example.springcache.service; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import com.example.springcache.domain.Student; @Service public class StudentService { @Cacheable("student") public Student getStudentByID(String id) { try { System.out.println("Going to sleep for 5 Secs.. to simulate backend call."); Thread.sleep(1000*5); } catch (InterruptedException e) { e.printStackTrace(); } return new Student(id,"Sajal" ,"V"); } } ``` `StudentController.java` ```java package com.example.springcache.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.example.springcache.domain.Student; import com.example.springcache.service.StudentService; @RestController public class StudentController { @Autowired StudentService studentService; @GetMapping("/student/{id}") public Student findStudentById(@PathVariable String id) { System.out.println("Searching by ID : " + id); return studentService.getStudentByID(id); } } ``` 請注意: * 服務層方法使用`@Cacheable("student")`進行了注解,如上所述,此注解啟用了該特定方法中的緩存,并且緩存名稱為`Student`。 * 在`getStudentByID()`方法中,使用`Thread.sleep(1000*5)`有意延遲 5 秒。 這僅僅是為了了解響應是來自緩存還是真實的后端。 #### 5.3 啟用 Spring 托管緩存 為此,我們只需要在 Spring Boot 應用程序類中添加`@EnableCaching`注解。 `SpringCacheApplication.java` ```java package com.example.springcache; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class SpringCacheApplication { public static void main(String[] args) { SpringApplication.run(SpringCacheApplication.class, args); } } ``` #### 5.4 演示 現在我們可以測試 Spring 緩存的默認緩存行為。 我們已經添加了必需的配置,并且通過 Spring Boot 變得更加容易。 要進行測試,只需通過`$ mvn clean install`命令再次構建項目,然后從命令行 Java 命令運行應用程序,或者僅從 IDE 中運行`SpringCacheApplication`。 它將在`localhost 8080`端口中啟動應用程序。 要測試,請轉到 url ```java http://localhost:8080/student/1 ``` 您將獲得一個`Student`對象的`JSON`響應。 需要注意的是,第一次響應至少需要 5 秒鐘,然后相同 URL 的后續響應會更快。 如果您難以理解差異,則可以更改服務等級中的延遲時間。 現在更改 URL 以通過`http://localhost:8080/student/2`獲得學生 ID 2,您將再次遇到延遲,但是在隨后的調用中,響應將從緩存提供。 這是我系統上關于此的最后幾行日志。 當調用實際服務時,我將獲得`Going to sleep for 5 Secs.. to simulate backend call.`日志,而在后續調用中,我未得到該日志,這意味著從緩存提供響應。 `Console` ```java Searching by ID : 1 Going to sleep for 5 Secs.. to simulate backend call. Searching by ID : 1 Searching by ID : 1 Searching by ID : 1 Searching by ID : 1 Searching by ID : 1 Searching by ID : 2 Going to sleep for 5 Secs.. to simulate backend call. Searching by ID : 2 Searching by ID : 2 ``` ## 7\. Spring Boot 緩存總結 最后,今天我們已經看到了 spring 框架在特定于應用程序緩存的緩存區域中提供了什么。 此外,我們還看到了 Spring 中存在哪些注解來支持這一點。 希望本教程對您有所幫助。 在本文中,我們使用了備用緩存提供程序,即后臺的`ConcurrentHashMap`。 下一步將是配置其他受支持的緩存引擎,例如 **Redis** , **Ehcache** 等。 [下載源碼](https://howtodoinjava.com/wp-content/uploads/2018/09/spring-cache.zip) 學習愉快! 參考文獻: [SpringBoot 緩存文檔](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-caching.html) [Spring 5 緩存文檔](https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/cache.html)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看