本地缓存caffeine快速入门
简便起见,直接在SpringBoot(版本号2.7.3)中演示caffeine的使用。
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
使用测试
package com.cas;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.junit.jupiter.api.Test;
import java.time.Duration;
public class CaffeineTest {
@Test
void testBasicOps() {
//构建缓存对象
Cache<String, String> cache = Caffeine.newBuilder().build();
//存储数据
cache.put("user", "tom");
//获取数据
System.out.println("user: " + cache.getIfPresent("user"));
//获取数据,未命中时执行回调函数,如查询数据库
String defaultUser = cache.get("defaultUser", key -> {
//根据key去数据库查询数据
return "张三";
});
System.out.println("defaultUser: " + defaultUser);
}
/**
* 基于大小的驱逐策略
*/
@Test
void testEvictByNum() throws InterruptedException {
//构建缓存对象
Cache<String, String> cache = Caffeine.newBuilder()
//设置缓存大小上限为1
.maximumSize(1).build();
//存储数据
cache.put("user1", "张三");
cache.put("user2", "李四");
cache.put("user3", "王五");
//延迟10ms,给清理线程一点时间
Thread.sleep(10L);
//获取数据
System.out.println("user1: " + cache.getIfPresent("user1"));
System.out.println("user2: " + cache.getIfPresent("user2"));
System.out.println("user3: " + cache.getIfPresent("user3"));
}
/**
* 基于有效期的驱逐策略
*/
@Test
void testEvictByTime() throws InterruptedException {
//构建缓存对象
Cache<String, String> cache = Caffeine.newBuilder()
//设置缓存有效期为1秒
.expireAfterWrite(Duration.ofSeconds(1)).build();
//存储数据
cache.put("user", "张三");
//获取数据
System.out.println("user: " + cache.getIfPresent("user"));
//休眠一会儿
Thread.sleep(1200L);
System.out.println("user: " + cache.getIfPresent("user"));
}
}
使用建议
可以创建CaffeineConfig配置类,在其中定义各种要用的缓存对象,如 Cache<String, Item>,Cache<String, User>等。
package com.cas.config;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CaffeineConfig {
@Bean
public Cache<String, Object> objectCache() {
return Caffeine.newBuilder()
.initialCapacity(100)
.maximumSize(10000)
.build();
}
}
需使用时直接通过@Autowired等注解装配即可。
参考资料
- https://www.jianshu.com/p/1ceaed0289b7
- https://www.bilibili.com/video/BV19Y41127Q8