Caffeine 缓存是 Java 的高性能缓存库。本文简单记录下 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 对象以及 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;
}
}
使用缓存
首先,我们创建一个 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);
}
}
其次,我们创建一个 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;
}
}
然后就可以测试了。我们根据打印的日志来判断缓存是否生效了。
总结
当我们想从缓存中查询某条数据时,可以注入CacheManager
,通过缓存名称来获取对应缓存,再根据key获取value。就像findAddressFromCache
里那样。
这只是个简单例子,实际使用的时候还要多关注他的配置参数,最基本的就是缓存的过期时间,这样才能更好的使用它。