Spring Boot 使用Guava缓存

1. 添加依赖

        
            org.springframework.boot
            spring-boot-starter-cache
        

2. 配置类

package com.llscz.datejiang.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author sukaiyi
 */
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager getCacheManager() {
        GuavaCacheManager cacheManager = new GuavaCacheManager();

        //最多缓存500 条,失效时间120分钟
        cacheManager.setCacheSpecification("maximumSize=500,expireAfterWrite=120m");
        //GuavaCacheManager 的数据结构类似  Map>  map =new HashMap<>();
        return cacheManager;
    }
}

3. 使用

    @Autowired
    CacheManager cacheManager;
//存
cacheManager.getCache("wx.app").put("access_token", accessToken);
//取
Cache.ValueWrapper wrapper = cacheManager.getCache("wx.app").get("access_token");
if (wrapper == null) {
    // 没有缓存
} else {
    String value = wrapper.get().toString();
}

你可能感兴趣的:(Spring Boot 使用Guava缓存)