Spring Boot 使用Guava缓存

2018-01-11  本文已影响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();
}
上一篇 下一篇

猜你喜欢

热点阅读