Spring Boot+Guava Cache+@EnableCaching

Spring Boot集成Guava Cache并配合@EnableCaching注解管理本地缓存

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.6-jre</version>
</dependency>

Guava缓存集成

GuavaCacheConfig:

@EnableConfigurationProperties(GuavaProperties.class)
@EnableCaching
@Configuration
public class GuavaCacheConfig {


    @Autowired
    private GuavaProperties guavaProperties;

    @Bean
    public CacheBuilder<Object, Object> cacheBuilder() {
       long maximumSize = guavaProperties.getMaximumSize();
        long duration = guavaProperties.getExpireAfterAccessDuration();
        if (maximumSize <= 0) {
            maximumSize = 1024;
        }
        if (duration <= 0) {
            duration = 1800;
        }
       return CacheBuilder.newBuilder()
                .maximumSize(maximumSize)
                .expireAfterAccess(duration, TimeUnit.SECONDS);
    }

    /**
     * expireAfterAccess: 当缓存项在指定的时间段内没有被读或写就会被回收。
     * expireAfterWrite:当缓存项在指定的时间段内没有更新就会被回收,如果我们认为缓存数据在一段时间后数据不再可用,那么可以使用该种策略。
     * refreshAfterWrite:当缓存项上一次更新操作之后的多久会被刷新。
     * @return
     */
    @DependsOn({"cacheBuilder"})
    @Bean
    public CacheManager cacheManager(CacheBuilder<Object, Object> cacheBuilder) {
        GuavaCacheManager cacheManager = new GuavaCacheManager();
        cacheManager.setCacheBuilder(cacheBuilder);
        return cacheManager;
    }

}

GuavaProperties:

@ConfigurationProperties(prefix = "guava.cache.config")
public class GuavaProperties {

    private long maximumSize;

    private long maximumWeight;

    private long expireAfterWriteDuration;

    private long expireAfterAccessDuration;

    private long refreshDuration;


    private int initialCapacity;

    private int concurrencyLevel;

    // get/set忽略
}

为了方便测试设置缓存过期时间为10秒

application.properties:

server.port=8081
guava.cache.config.expire-after-access-duration=10

缓存测试

CacheService:

@Service
public class CacheService {
    @CachePut(value = "guavacache")
    public long save() {
        long timestamp = new Timestamp(System.currentTimeMillis()).getTime();
        System.out.println("进行缓存:" + timestamp);
        return timestamp;
    }

    @CacheEvict(value = "guavacache")
    public void delete() {
        System.out.println("删除缓存");
    }

    @Cacheable(value = "guavacache")
    public long getByCache() {
        try {
            Thread.sleep(3 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Timestamp(System.currentTimeMillis()).getTime();
    }
}

CacheController:

@RestController
@RequestMapping("/cache")
public class CacheController {
    @Autowired
    private CacheService cacheService;

    /**
     * 查询方法
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String getByCache() {
        Long startTime = System.currentTimeMillis();
        long timestamp = this.cacheService.getByCache();
        Long endTime = System.currentTimeMillis();
        System.out.println("耗时: " + (endTime - startTime));
        return timestamp+"ms";
    }

    /**
     * 保存方法
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public void save() {
        this.cacheService.save();
    }

    /**
     * 删除方法
     */
    @RequestMapping(value = "", method = RequestMethod.DELETE)
    public void delete() {
        this.cacheService.delete();
    }
}

get方法访问localhost:8081/cache/,控制台输出:

耗时: 3007ms

在10s内访问,输出:

耗时: 1ms

说明,getByCache方法直接从缓存获取结果,线程没有执行到sleep方法,缓存成功。

其它方法可自行测试。

源码地址:
https://gitee.com/yidasanqian/spring-boot-guava-cache-demo.git

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值