Spring Boot 中使用Caffeine缓存的简单例子
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
里那样。
这只是个简单例子,实际使用的时候还要多关注他的配置参数,最基本的就是缓存的过期时间,这样才能更好的使用它。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~