A high performance caching library for Java
译文:一个用于Java的高性能缓存库
资料
- 中文文档:https://github.com/ben-manes/caffeine/wiki/Home-zh-CN
- github:https://github.com/ben-manes/caffeine
- https://mvnrepository.com/artifact/com.github.ben-manes.caffeine/caffeine
依赖
<dependencies>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
代码示例
package com.example.caffeine;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
public class CaffeineTest {
@Test
public void testCache() {
Cache<String, String> cache = Caffeine.newBuilder()
.expireAfterWrite(3, TimeUnit.SECONDS)
.maximumSize(10_000)
.build();
String key = "key";
// 查找一个缓存元素, 没有查找到的时候返回null
String value = cache.getIfPresent(key);
System.out.println(value);
// null
// 查找缓存,如果缓存不存在则生成缓存元素, 如果无法生成则返回null
value = cache.get(key, k -> "value");
System.out.println(value);
// value
// 移除一个缓存元素
cache.invalidate(key);
value = cache.getIfPresent(key);
System.out.println(value);
// null
// 添加或者更新一个缓存元素
cache.put(key, "newValue");
value = cache.getIfPresent(key);
System.out.println(value);
// newValue
// 延迟4秒
try {
Thread.sleep(4 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 再次获取缓存为null
value = cache.getIfPresent(key);
System.out.println(value);
// null
}
}