今天優銳課給大家分享這篇新文章——《快速入門:如何在Redis上使用Spring Cache》
Spring是Java編程語言的一種非常流行的應用程序框架,它使構建企業Java軟件更加容易。從3.1版開始,Spring支持將緩存添加到現有的Spring應用程序中,以提高性能並減少響應時間。
Redis是一種開源的內存中數據結構存儲,可用於構建NoSQL數據庫。但是,Redis不包括對Java的常規支持或對Spring等應用程序框架的支持。
好消息是,你可以使用第三方Redis Java客戶端(例如Redisson)來使用Spring和Redis進行緩存。Redisson與Spring框架完全兼容。在本文中,我們將討論如何在Redis中使用Redisson進行緩存。
在Spring中緩存
Spring框架提供了一個緩存抽象層。在Spring中進行緩存的相關注釋如下:
· @Cacheable:@Cacheable批註表示調用此方法的結果將被緩存。 如果再次使用相同的參數調用該方法,則將從緩存中檢索結果,而不是調用該方法。
· @CachePut:@CachePut批註表示方法將觸發緩存放置操作。
· @CacheEvict:@CacheEvict批註表示方法將觸發緩存逐出操作。
· @EnableCaching:@EnableCaching批註啓用Spring的內置緩存管理功能。
· @Caching:@Caching註釋是用於多個緩存註釋的組註釋。
· @CacheConfig:@CacheConfig批註允許共享與緩存相關的常見設置,例如緩存名稱和密鑰生成器。
安裝Redisson
安裝Redisson非常簡單。例如,如果你使用的是Maven,只需將以下依賴項添加到pom.xml文件中:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.5</version>
</dependency>
Redisson中的緩存參數
Redisson中的每個Spring緩存都有兩個重要的參數,以毫秒爲單位指定:
· ttl:ttl(生存時間)參數確定高速緩存中對象的最大生存期。 緩存中的所有對象的生存時間到期後,無論請求的頻率如何,都將刪除它們。
· maxIdleTime:maxIdleTime參數確定兩次請求對象之間可以經過的最長時間。如果這段時間沒有請求,對象將從緩存中自動刪除。此參數僅在Spring緩存的Redisson實現中存在。
如果這兩個參數未定義或等於0,則將無限期存儲高速緩存中的對象。
使用Spring和Redis進行緩存的示例代碼
以下示例代碼演示瞭如何使用Redisson在Spring和Redis中執行緩存。該代碼利用了兩個Spring bean:第一個用於創建和配置Redisson客戶端,第二個用於設置和測試緩存。
@Configuration
@ComponentScan
@EnableCaching
public class Application {
@Bean(destroyMethod="shutdown")
RedissonClient redisson() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient) {
Map<String, CacheConfig> config = new HashMap<>();
// create "testMap" spring cache with ttl = 24 minutes and maxIdleTime = 12 minutes
config.put("testMap", new CacheConfig(24*60*1000, 12*60*1000));
return new RedissonSpringCacheManager(redissonClient, config);
}
}
結論
藉助本地緩存的功能,Redisson允許你將基於Redis的Spring緩存的性能提高多達45倍,以進行讀取操作。
感謝閱讀!歡迎留言或私信。
抽絲剝繭 細說架構那些事——【優銳課】