好久没有写文章了,前段时间由于公司项目比较忙,因此耽搁了一些时间。本篇文章也是本头条号转正后发的第一篇文章,在此跟各位看官道歉,同时也感谢各位看官的不离不弃。希望各位看官可以关注本头条号以便持续获取最新资讯。
当各位看官打开这篇文章时,相信对SpringBoot的使用已经足够了解了,我就不做过多的赘述了,这篇文章主要是讲解如何在SpringBoot框架中集成GuavaCache从而实现本地缓存。相信大家都明白,在多线程高并发的情况下缓存(cache)的存在是必须的,但是需要根据不同的应用场景来使用不同的缓存策略。现阶段经常使用的缓存策略有很多,也很成熟。比如分布式缓存:redis、memcached,本地缓存:ehcache、CaffeineCache以及本篇文章将要讲到的GuavaCache。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据 (设置为true时会移除所有缓存)
-
import java.util.ArrayList;
-
import java.util.concurrent.TimeUnit;
-
import org.springframework.cache.CacheManager;
-
import org.springframework.cache.annotation.EnableCaching;
-
import org.springframework.cache.guava.GuavaCache;
-
import org.springframework.cache.support.SimpleCacheManager;
-
import org.springframework.context.annotation.Bean;
-
import org.springframework.context.annotation.Configuration;
-
import com.google.common.cache.CacheBuilder;
-
/**
-
* <p>guava缓存配置</p>
-
* @author Bruce
-
*
-
*/
-
@Configuration
-
@EnableCaching
-
public class GuavaConfig {
-
private static final int DEFAULT_MAXSIZE = 1000;
-
private static final int DEFAULT_TTL = 3600;
-
/**
-
* 个性化配置缓存
-
*/
-
@Bean
-
public CacheManager cacheManager() {
-
SimpleCacheManager manager = new SimpleCacheManager();
-
//把各个cache注册到cacheManager中,GuavaCache实现了org.springframework.cache.Cache接口
-
ArrayList<GuavaCache> caches = new ArrayList<>();
-
for (Caches c : Caches.values()) {
-
caches.add(new GuavaCache(c.name(), CacheBuilder.newBuilder().recordStats().expireAfterWrite(c.getTtl(), TimeUnit.SECONDS).maximumSize(c.getMaxSize()).build()));
-
}
-
manager.setCaches(caches);
-
return manager;
-
}
-
/**
-
* 定义cache名称、超时时长秒、最大个数
-
* 每个cache缺省3600秒过期,最大个数1000
-
*/
-
public enum Caches {
-
API_PAGESUB(7200),
-
API_MATERIAL(30);
-
private int maxSize = DEFAULT_MAXSIZE; //最大數量
-
private int ttl = DEFAULT_TTL; //过期时间(秒)
-
Caches() {
-
}
-
Caches(int ttl) {
-
this.ttl = ttl;
-
}
-
Caches(int ttl, int maxSize) {
-
this.ttl = ttl;
-
this.maxSize = maxSize;
-
}
-
public int getMaxSize() {
-
return maxSize;
-
}
-
public void setMaxSize(int maxSize) {
-
this.maxSize = maxSize;
-
}
-
public int getTtl() {
-
return ttl;
-
}
-
public void setTtl(int ttl) {
-
this.ttl = ttl;
-
}
-
}
-
}
-
三、springboot启动器配置
-
package com.zhibo.xmt;
-
import org.springframework.boot.SpringApplication;
-
import org.springframework.boot.autoconfigure.SpringBootApplication;
-
import org.springframework.cache.annotation.EnableCaching;
-
import com.unionpay.acp.sdk.SDKConfig;
-
/**
-
* springboot启动器
-
* @author Bruce
-
*
-
*/
-
@SpringBootApplication
-
@EnableCaching
-
public class App {
-
public static void main(String[] args) {
-
System.out.println("xmt api start........");
-
SDKConfig.getConfig().loadPropertiesFromSrc();
-
SpringApplication.run(App.class, args);
-
}
-
}