文章目录
JetCache 是一个基于 Java 的高性能缓存框架,支持多种缓存类型(内存、Redis、Tair 等)和注解驱动。以下是详细的配置步骤:
1. 添加依赖
在 Maven 项目的 pom.xml
中添加依赖(以 Spring Boot + Redis 为例):
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis</artifactId>
<version>2.6.4</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置文件(application.yml)
jetcache:
statIntervalMinutes: 15 # 缓存统计间隔(分钟)
areaInCacheName: false # 是否在缓存名中包含区域(area)前缀
# 本地缓存配置(可选)
local:
default:
type: linkedhashmap # 本地缓存类型:caffeine/linkedhashmap
keyConvertor: fastjson # 键转换器:fastjson/jackson
limit: 100 # 本地缓存最大元素数
# Redis 远程缓存配置
remote:
default:
type: redis # 缓存类型:redis
keyConvertor: fastjson
valueEncoder: java # 值编码:java/kryo
valueDecoder: java
poolConfig:
minIdle: 5
maxIdle: 20
maxTotal: 50
host: 127.0.0.1 # Redis 地址
port: 6379
password: "" # Redis 密码(若无则留空)
database: 0 # Redis 数据库索引
# 多区域配置(可选)
areas:
- id: areaA # 区域 A
local:
limit: 200
remote:
keyPrefix: "cacheA:" # Redis 键前缀
expire: 3600 # 默认过期时间(秒)
- id: areaB # 区域 B
remote:
keyPrefix: "cacheB:"
expire: 7200
3. 启用 JetCache
在 Spring Boot 启动类上添加注解:
@SpringBootApplication
@EnableMethodCache(basePackages = "com.example.service") // 扫描 @Cached 注解
@EnableCreateCacheAnnotation // 支持 @CreateCache 注解
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4. 使用注解驱动缓存
4.1 方法缓存(@Cached)
默认使用remote缓存既redis, 如需切换通过cacheType属性指定
@Service
public class UserService {
@Cached(name = "userCache:", key = "#userId", expire = 1800)
public User getUserById(Long userId) {
// 数据库查询逻辑
return userDao.findById(userId);
}
@CacheUpdate(name = "userCache:", key = "#user.id", value = "#user")
public void updateUser(User user) {
userDao.update(user);
}
@CacheInvalidate(name = "userCache:", key = "#userId")
public void deleteUser(Long userId) {
userDao.delete(userId);
}
}
4.2 手动创建缓存实例(@CreateCache)
默认也是使用remote缓存既redis, 同样通过cacheType属性指定
@Component
public class CacheService {
@CreateCache(name = "orderCache:", expire = 3600)
private Cache<Long, Order> orderCache;
public Order getOrder(Long orderId) {
return orderCache.get(orderId);
}
public void updateOrder(Order order) {
orderCache.put(order.getId(), order);
}
}
5. 高级配置
5.1 缓存穿透保护
jetcache:
remote:
default:
cacheNullValue: true # 缓存空值(防止穿透)
penetrationProtect: true # 启用穿透保护
5.2 多级缓存(本地 + Redis)
@Cached(name = "userCache:", key = "#userId",
cacheType = CacheType.BOTH, // 同时使用本地和远程缓存
localLimit = 100,
expire = 3600)
public User getUser(Long userId) { ... }
5.3 自定义序列化
@Configuration
public class JetCacheConfig {
@Bean
public RedisConfig customRedisConfig() {
RedisConfig config = new RedisConfig();
config.setValueEncoder(ValueEncoder.KRYO); // 使用 Kryo 序列化
config.setValueDecoder(ValueDecoder.KRYO);
return config;
}
}
6. 常见问题
Q1: 缓存不生效?
- 检查
@EnableMethodCache
的包路径是否正确。 - 确保方法未被同类内部调用(AOP 代理失效)。
Q2: Redis 连接失败?
- 检查 Redis 地址、端口、密码配置。
- 确保 Redis 服务已启动。
Q3: 序列化异常?
- 使用
java
序列化时,确保对象实现Serializable
。 - 使用
kryo
时,注册自定义类:ConfigProvider.setKryoRegister(() -> kryo.register(User.class))
。
7. 完整配置参考
官方文档 提供了更多高级配置选项(如集群模式、Tair 支持、缓存预热等)。