Spring Boot 中使用Caffeine缓存的简单例子

Caffeine 缓存是 Java 的高性能缓存库。本文简单记录下 Caffeine 缓存的用法。

依赖配置

xml 复制代码
<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 缓存管理器。

java 复制代码
@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.

java 复制代码
@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.

java 复制代码
@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里那样。

这只是个简单例子,实际使用的时候还要多关注他的配置参数,最基本的就是缓存的过期时间,这样才能更好的使用它。

相关推荐
whltaoin6 天前
【JAVA全栈项目】弧图图-智能图床SpringBoot+MySQL API接口结合Redis+Caffeine多级缓存实践解析
java·redis·spring·缓存·caffeine·多级缓存
程语有云23 天前
生产事故-Caffeine缓存误用之临下班的救赎
java·缓存·caffeine·阻塞·log·生产事故
C++chaofan1 个月前
项目中为AI添加对话记忆
java·数据结构·人工智能·redis·缓存·个人开发·caffeine
没事学AI2 个月前
Caffeine三种缓存过期策略总结:原理、实战与调优
java·缓存·caffeine·缓存穿透防护·caffeine缓存
鼠鼠我捏,要死了捏2 个月前
Caffeine 本地缓存最佳实践与性能优化指南
缓存·性能优化·caffeine
forestsea4 个月前
Caffeine 缓存库的常用功能使用介绍
java·缓存·caffeine
woai33645 个月前
首页实现多级缓存
redis·缓存·caffeine
for627 个月前
本地缓存大杀器-Caffeine
缓存·caffeine·本地缓存
老友@8 个月前
Caffeine 缓存:简介、优势及应用场景
后端·spring·缓存·优化·caffeine·三级缓存
吴晓斌kobe9 个月前
Java中的缓存技术:Guava Cache vs Caffeine vs Redis
java·redis·缓存·guava·caffeine