美文网首页
Spring Boot 使用Guava缓存

Spring Boot 使用Guava缓存

作者: 王不哈 | 来源:发表于2018-01-11 16:30 被阅读784次

    1. 添加依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-cache</artifactId>
            </dependency>
    

    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<String,Map<Object,Object>>  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缓存

          本文链接:https://www.haomeiwen.com/subject/dghtoxtx.html