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

本文介绍了如何在Java应用中使用Caffeine缓存库,包括依赖配置、代码实现(初始化Caffeine对象和CacheManager,以及使用@Cacheable注解),并展示了如何在Service和Controller中利用缓存提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值