您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# GuavaCache怎么使用
## 1. 什么是GuavaCache
Guava Cache是Google Guava库中的一个本地缓存实现,提供了线程安全、高性能的缓存机制。与传统的`Map`实现不同,Guava Cache支持以下特性:
- **自动回收策略**:基于大小、时间或引用类型自动清理缓存
- **缓存加载机制**:支持自动加载未命中键的值
- **统计功能**:提供命中率等统计信息
- **监听器**:支持缓存移除通知
## 2. 基本使用
### 2.1 引入依赖
首先需要在项目中添加Guava依赖:
```xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
最简单的创建方式是通过CacheBuilder
:
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(1000) // 最大缓存项数
.expireAfterWrite(10, TimeUnit.MINUTES) // 写入10分钟后过期
.build();
// 放入缓存
cache.put("key1", "value1");
// 获取缓存(如果不存在返回null)
String value = cache.getIfPresent("key1");
// 获取或计算(当键不存在时)
String value = cache.get("key2", () -> computeExpensiveValue("key2"));
Guava Cache提供了三种主要的回收方式:
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100) // 基于LRU算法回收
.build();
Cache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterAccess(5, TimeUnit.MINUTES) // 最后一次访问后5分钟过期
.expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期
.build();
Cache<String, String> cache = CacheBuilder.newBuilder()
.weakKeys() // 使用弱引用存储键
.weakValues() // 使用弱引用存储值
.softValues() // 使用软引用存储值
.build();
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) {
return computeExpensiveValue(key); // 当缓存未命中时自动调用
}
});
// 使用方式
String value = cache.get("key1"); // 自动加载
Cache<String, String> cache = CacheBuilder.newBuilder().build();
String value = cache.get("key1", () -> computeExpensiveValue("key1"));
// 单个移除
cache.invalidate("key1");
// 批量移除
cache.invalidateAll(Arrays.asList("key1", "key2"));
// 清除所有
cache.invalidateAll();
Cache<String, String> cache = CacheBuilder.newBuilder()
.removalListener(notification -> {
System.out.println("Key " + notification.getKey() + " was removed. Cause: " + notification.getCause());
})
.build();
Cache<String, String> cache = CacheBuilder.newBuilder()
.recordStats() // 开启统计
.build();
// 获取统计信息
CacheStats stats = cache.stats();
System.out.println("命中率: " + stats.hitRate());
System.out.println("平均加载时间: " + stats.averageLoadPenalty() + "ns");
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.refreshAfterWrite(1, TimeUnit.MINUTES) // 写入1分钟后刷新
.build(cacheLoader);
// 手动刷新
cache.refresh("key1");
LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.refreshAfterWrite(1, TimeUnit.MINUTES)
.build(CacheLoader.asyncReloading(cacheLoader, executor));
LoadingCache<Long, User> userCache = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<Long, User>() {
@Override
public User load(Long id) {
return userDao.findById(id);
}
});
Cache<String, AtomicInteger> rateLimitCache = CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnit.SECONDS)
.build();
public boolean allowRequest(String ip) {
AtomicInteger count = rateLimitCache.get(ip, () -> new AtomicInteger(0));
return count.incrementAndGet() <= 10; // 每秒不超过10次
}
Guava Cache提供了强大而灵活的本地缓存解决方案,通过合理的配置可以显著提升应用性能。其丰富的特性如自动回收、加载机制和统计功能,使其成为Java应用中缓存实现的首选方案之一。
”`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。