Spring boot的快取使用
Spring框架為不同的快取產品提供快取抽象api,API的使用非常簡單,但功能非常強大。今天我們將在快取上看到基於註釋的Java配置,請注意,我們也可以通過XML配置實現類似的功能。
@EnableCaching
它支援Spring的註釋驅動的快取管理功能,在spring boot專案中,我們需要將它新增到帶註釋的引導應用程式類中@SpringBootApplication。Spring預設提供了一個併發hashmap作為預設快取,但我們也可以覆蓋CacheManager以輕鬆註冊外部快取提供程式。
@Cacheable
它在方法級別上使用,讓spring知道該方法的響應是可快取的。Spring將此方法的請求/響應管理到註釋屬性中指定的快取。例如,@Cacheable ("cache-name1", “cache-name2”)。
@Cacheable註釋有更多選項。就像我們可以從方法的請求中指定快取的鍵,如果沒有指定,spring使用所有類欄位並將其用作快取鍵(主要是HashCode)來維護快取,但我們可以通過提供關鍵資訊來覆蓋此行為:
@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)
我們也可以使用條件快取。例如,
@Cacheable(value="book", condition="#name.length < 50")
public Book findStoryBook (String name)
@CachePut
有時我們需要手動操作快取,這樣可在方法呼叫之前put(更新)快取,這個方法讓我們更新快取,並且執行被註釋的該方法,Spring執行註釋方法,並將其結果放入快取中(根據@CachePut選項)。
它與@Cacheable支援相同的選項,應該用於快取填充,而不是方法流優化。
請注意,通常不鼓勵對同一方法使用@CachePut和@Cacheable註釋,因為它們具有不同的行為。雖然後者導致通過使用快取跳過方法執行,但前者強制執行以執行快取更新。
這會導致意外的行為,除了特定的角落情況(例如註釋具有將它們彼此排除的條件)之外,應該避免這種宣告。
@CacheEvict
當我們需要從快取刪除先前載入的主資料時可以使用它,當CacheEvict註釋方法將被執行時,它將清除快取。
我們可以在這裡指定鍵來刪除快取,如果我們需要刪除快取的所有條目,那麼我們需要使用allEntries=true。當需要清除整個快取區域時,此選項會派上用場 - 而不是逐個剔除每個條目(這會花費很長時間,因為它效率低),所有條目都在一次操作中被刪除。
@Caching
當同時需要CachePut和CacheEvict時,使用這個註釋。
Spring啟動提供與以下快取提供程式的整合。Spring引導使用預設選項進行自動配置,如果這些選項存在於類路徑中,並且我們已在spring boot應用程式中通過@EnableCaching啟用了快取。
JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
EhCache 2.x
Hazelcast
Infinispan
Couchbase
Caffeine
Simple cache
我們可以通過覆蓋快取提供程式特定的設定來覆蓋Spring starter中的特定快取行為 - 例如
spring.cache.infinispan.config=infinispan.xml
使用案例
1. 使用快取:
@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");
}
}
服務層方法被註釋@Cacheable("student"),該註釋在該特定方法中啟用快取記憶體,並且快取記憶體名稱是"student"。
在該getStudentByID()方法中,我們使用有意的5秒延遲Thread.sleep(1000*5)。這只是為了瞭解響應是來自快取還是真正的後端。
2. REST前端:
@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);
}
}
3.啟用快取:
@SpringBootApplication
@EnableCaching
public class SpringCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCacheApplication.class, args);
}
}