多級緩存實際上是在二級緩存的基礎上,為了更好地提高系統的性能和可靠性,更适用于大型分布式系統的應用場景。
使用多級緩存的原因包括:
- 資料緩存分層:不同級别的緩存可以被用來緩存不同類型、不同頻率通路的資料。在這種情況下,系統會先在本地緩存中尋找資料,如果找不到再到其他級别的緩存中查找,并最終到資料庫中擷取資料。這種方式可以更快地響應不同類型的請求,并且讓處理分布式系統通路的資料變得更容易。
- 優化系統響應時間:多級緩存的分層結構使之非常适用于盡快響應使用者資料請求的場景。對于通路頻率較高的資料,緩存在更接近應用程式的本地緩存中,可以快速擷取;對于通路頻率較低的資料,存儲在較遠緩存層級上,直到有需要時才會通路;在最後一級緩存搜尋失敗後,才會從資料庫中擷取所需的資料。這種方式在響應時間方面非常優秀。
- 提高可靠性和容錯性:多級緩存通常包括主緩存和備用緩存,如果主緩存挂了,系統會自動切換到備用緩存,保證系統正常運作,資料不會丢失。
- 降低資源開銷:多級緩存可以大大降低系統資源的使用成本。将頻繁通路的資料将存入低延遲、高效的本地緩存中,避免大量的RPC(遠端過程調用)和資料庫查詢。
總的來說,多級緩存旨在提高系統的性能和可靠性,并降低資源使用率。在大規模、高計算量、分布式系統中使用多級緩存是必不可少的
Spring Boot是Spring Framework的增強版本,可以快速開發基于Spring的應用程式。在Spring Boot中使用Jetcache的二級緩存也是極為簡單的。
下面是Spring Boot Jetcache二級緩存的用法:
- 添加Jetcache和Hazelcast的依賴
在pom.xml檔案中添加Jetcache和Hazelcast的依賴。
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-spring</artifactId>
<version>4.1.1</version>
</dependency>
- 配置JetCache
在application.properties配置檔案中添加JetCache的配置,來配置二級緩存。
# JetCache配置 jetcache.cacheType=default jetcache.default.local.expireAfterWrite=10m
jetcache.default.local.expireAfterAccess=10m jetcache.default.local.limit=1000
jetcache.default.local.nullable=true
jetcache.default.local.keyConvertor=tiger.pathos.car.impl.JacksonKeyConvertor
jetcache.default.remote.expireAfterWrite=10m
jetcache.default.remote.expireAfterAccess=10m
jetcache.default.remote.serializer=hazelcast
jetcache.default.remote.addresses=localhost:5701
cacheType指定緩存提供者,預設為default。expireAfterWrite和expireAfterAccess表示寫入時間和最後通路時間後的到期時間。limit為本地緩存大小。nullable表示是否緩存null值。keyConvertor指定使用的鍵值轉換器。remote.serializer表示遠端緩存使用的序列化器。remote.addresses指定遠端緩存的位址。
- 使用注解添加緩存
在需要緩存處理的方法上使用JetCache提供的注解。
示例方法:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
@Cached(name = "userCache:", key = "#id", expire = 7200, cacheType = CacheType.BOTH)
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
在這個示例中,使用@Cached注解将getUserById方法中的結果緩存。name即為緩存的名稱,key為緩存的鍵值,expire為緩存過期的時間,cacheType即為緩存類型。
- 測試
使用Junit等測試架構編寫測試用例,測試Spring Boot應用程式中的JetCache二級緩存是否成功啟用,緩存是否生效。
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
public void testGetUserById() {
Long id = 1L;
User user = userService.getUserById(id);
// TODO 測試緩存是否生效
}
}
至此,Spring Boot應用程式就已經成功使用了JetCache的二級緩存。
加群交流