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


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

    依赖配置

    
        
            org.springframework.boot
            spring-boot-starter-cache
        
        
            com.github.ben-manes.caffeine
            caffeine
        
    
    

    代码配置

    我们需要初始化 Caffeine 对象以及 Caffeine 缓存管理器。

    @Configuration
    public class CaffeineConfig {
    
        @Bean
        public Caffeine caffeine() {
            return Caffeine.newBuilder().expireAfterWrite(60, TimeUnit.MINUTES);
        }
    
        @Bean
        public CacheManager cacheManager(Caffeine caffeine) {
            CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
            caffeineCacheManager.setCaffeine(caffeine);
            return caffeineCacheManager;
        }
    }
    

    使用缓存

    首先,我们创建一个 Service.

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

  • 相关阅读:
    《痞子衡嵌入式半月刊》 第 53 期
    海外腾讯云服务器手机上无法访问外网怎么办??
    【408数据结构与算法】—栈与递归(十二)
    适配器模式已经在SpringMVC中的源码实现
    智慧城市平台的技术路线和系统要求
    Flutter 跨平台框架中的 Widgets,你了解多少?
    java临时文件
    【科普知识】什么是模拟量控制?
    【环境】Ubuntu20.04 安装 Anaconda 顺顺利利
    计算机毕业设计Java高校防疫物资管理系统(源码+系统+mysql数据库+lw文档)
  • 原文地址:https://www.cnblogs.com/cloudrich/p/17977283