當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
Spring Boot 中使用Caffeine缓存的简单例子
生活随笔
收集整理的這篇文章主要介紹了
Spring Boot 中使用Caffeine缓存的简单例子
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Caffeine 緩存是 Java 的高性能緩存庫(kù)。本文簡(jiǎn)單記錄下 Caffeine 緩存的用法。
依賴配置
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
</dependencies>
代碼配置
我們需要初始化 Caffeine 對(duì)象以及 Caffeine 緩存管理器。
@Configuration
public class CaffeineConfig {
@Bean
public Caffeine<Object, Object> caffeine() {
return Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES);
}
@Bean
public CacheManager cacheManager(Caffeine<Object, Object> caffeine) {
CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
caffeineCacheManager.setCaffeine(caffeine);
return caffeineCacheManager;
}
}
使用緩存
首先,我們創(chuàng)建一個(gè) Service.
@Service
@Slf4j
public class AddressService {
private static final Map<Long, AddressDTO> ADDRESS_TABLE = new HashMap<>();
static {
ADDRESS_TABLE.put(1L, new AddressDTO(1, "廣東"));
ADDRESS_TABLE.put(2L, new AddressDTO(2, "深圳"));
ADDRESS_TABLE.put(3L, new AddressDTO(3, "坂田"));
}
@Cacheable(value = "address_cache", key = "#addressId")
public AddressDTO getAddress(long addressId) {
log.info("AddressService getAddress, addressId: {}", addressId);
return ADDRESS_TABLE.get(addressId);
}
}
其次,我們創(chuàng)建一個(gè) Controller.
@RestController
public class CaffeineController {
@Autowired
private AddressService addressService;
@Autowired
private CacheManager cacheManager;
@GetMapping("/{addressId}")
public AddressDTO getAddress(@PathVariable long addressId) {
return addressService.getAddress(addressId);
}
@GetMapping("/cache/{addressId}")
public AddressDTO findAddressFromCache(@PathVariable long addressId) {
Cache addressCache = cacheManager.getCache("address_cache");
if (addressCache != null) {
return (AddressDTO)addressCache.get(addressId).get();
}
return null;
}
}
然后就可以測(cè)試了。我們根據(jù)打印的日志來判斷緩存是否生效了。
總結(jié)
當(dāng)我們想從緩存中查詢某條數(shù)據(jù)時(shí),可以注入CacheManager,通過緩存名稱來獲取對(duì)應(yīng)緩存,再根據(jù)key獲取value。就像findAddressFromCache里那樣。
這只是個(gè)簡(jiǎn)單例子,實(shí)際使用的時(shí)候還要多關(guān)注他的配置參數(shù),最基本的就是緩存的過期時(shí)間,這樣才能更好的使用它。
總結(jié)
以上是生活随笔為你收集整理的Spring Boot 中使用Caffeine缓存的简单例子的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bitcask论文翻译/笔记
- 下一篇: Transformer的应用