在Ubuntu上使用Java缓存技术可结合本地缓存库或分布式缓存系统,以下是具体方法及示例:
本地缓存(轻量级场景)
Guava Cache:适合简单键值缓存,支持过期策略(如基于时间或容量)。
// 添加依赖:Maven中引入 guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
// 代码示例
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
cache.put("key1", "value1");
String value = cache.getIfPresent("key1");
Caffeine:高性能本地缓存,支持异步加载和多种淘汰策略(如LRU)。
// 添加依赖:Maven中引入 caffeine -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>3.1.8</version>
</dependency>
// 代码示例
Cache<String, String> cache = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.build();
分布式缓存(高并发/分布式场景)
// 添加依赖:Maven中引入 jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.1</version>
</dependency>
// 代码示例
Jedis jedis = new Jedis("localhost", 6379);
jedis.set("key1", "value1");
jedis.expire("key1", 3600); // 设置过期时间(秒)
String value = jedis.get("key1");
缓存策略与工具集成
// 添加依赖:Spring Boot Starter Cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
// 配置缓存管理器(以Redis为例)
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.create(factory);
}
// 使用注解缓存方法结果
@Cacheable(value = "myCache", key = "#id")
public String getDataById(String id) {
// 数据库查询逻辑
}
注意事项