Caffine
Caffeine 简介
什么是 Caffeine
Caffeine 是一个高性能的 Java 缓存库,提供了近乎最优的命中率。它是一个完全在内存中的缓存,可以用作本地缓存或与其他缓存解决方案结合使用。Caffeine 的主要特点包括:
- 快速的读写操作
- 基于大小、时间和引用的驱逐策略
- 统计和监听功能
- 易用的 API
tio-boot 整合 Caffeine
- 添加依赖:首先,需要在项目的
pom.xml
中添加 Caffeine 的依赖项。tio-boot 已经内置了 caffeine-2.9.3 依赖
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.3</version>
</dependency>
- 配置缓存:在你的 Java 配置类中,你可以创建一个 Caffeine 缓存实例。例如:
package com.litongjava.tio.boot.hello.config;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.litongjava.jfinal.aop.annotation.Bean;
import com.litongjava.jfinal.aop.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@AConfiguration
public class CaffeineCacheConfig {
@ABean
public Cache<String, Object> caffeineCache() {
return Caffeine.newBuilder()
.maximumSize(10000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
}
}
- 使用缓存:一旦缓存被配置,你就可以在应用中使用它来存储和检索数据。
package com.litongjava.tio.boot.hello.AController;
import com.github.benmanes.caffeine.cache.Cache;
import com.litongjava.jfinal.aop.Aop;
import com.litongjava.tio.http.common.HttpRequest;
import com.litongjava.tio.http.server.annotation.RequestPath;
import lombok.extern.slf4j.Slf4j;
@AController
@RequestPath("/caffeine")
@Slf4j
public class CaffeineTestController {
@RequestPath("/test")
public Object test(HttpRequest request) {
Cache<String, Object> cache = Aop.get(Cache.class);
Object value = cache.getIfPresent("key");
if (value == null) {
log.info("计算value");
cache.put("key", "11111");
}
return value;
}
}
访问测试: http://localhost//caffeine/test