spring-boot中配置和使用Caffeine Cache
第一步:引入依赖
这里不知道为什么很多版本的依赖包用不了,用不了的话你剋实施其他的
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.5.5</version>
</dependency>
第二部:配置相关文档:
有两种方法:
1.application.yml配置文件中配置:
优点:简单
缺点:无法针对每个cache配置不同的参数,比如过期时长、最大容量
2.配置类中配置
优点:可以针对每个cache配置不同的参数,比如过期时长、最大容量
缺点:要写一点代码
- 在yml文件中
spring:
cache:
type: caffeine
cache-names:
- getPersonById
- name2
caffeine:
spec: maximumSize=500,expireAfterWrite=5s
- 在启动类中加入@EnableCaching
- 在对应类中加入对应的缓存方法:
@CacheConfig(cacheNames = "emp")
@Service
public class EmployService {
@Autowired
EmploeeMapper emploeeMapper;
@Cacheable(cacheNames = {"emp"})
public Employee getEmpById(Integer id){
System.out.println("查询" + id + "号员工");
Employee employee = emploeeMapper.getEmpById(id);
System.out.print(employee);
return employee;
}
}
运行后:可以在debug控制台中看到CaffeineCacheConfig被引用了
第二种用配置文件配置,这种方法更加灵活:
package com.xjj.config;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.github.benmanes.caffeine.cache.Caffeine;
/**
* Cache配置類,用于缓存数据
* @author XuJijun
*
*/
@Configuration
@EnableCaching
public class CacheConfig {
public static final int DEFAULT_MAXSIZE = 50000;
public static final int DEFAULT_TTL = 10;
/**
* 定義cache名稱、超時時長(秒)、最大容量
* 每个cache缺省:10秒超时、最多缓存50000条数据,需要修改可以在 构造方法的参数中指定。
*/
public enum Caches{
getPersonById(5), //有效期5秒
getSomething, //缺省10秒
getOtherthing(300, 1000), //5分钟,最大容量1000
;
Caches() {
}
Caches(int ttl) {
this.ttl = ttl;
}
Caches(int ttl, int maxSize) {
this.ttl = ttl;
this.maxSize = maxSize;
}
private int maxSize=DEFAULT_MAXSIZE; //最大數量
private int ttl=DEFAULT_TTL; //过期时间(秒)
public int getMaxSize() {
return maxSize;
}
public int getTtl() {
return ttl;
}
}
/**
* 创建基于Caffeine的Cache Manager
* @return
*/
@Bean
@Primary
public CacheManager caffeineCacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
ArrayList<CaffeineCache> caches = new ArrayList<CaffeineCache>();
for(Caches c : Caches.values()){
caches.add(new CaffeineCache(c.name(),
Caffeine.newBuilder().recordStats()
.expireAfterWrite(c.getTtl(), TimeUnit.SECONDS)
.maximumSize(c.getMaxSize())
.build())
);
}
cacheManager.setCaches(caches);
return cacheManager;
}
}