SpringBoot3整合JetCache缓存
概述
JetCache是一个由阿里巴巴开发的基于Java的缓存系统封装,旨在通过统一的API和注解简化缓存的使用。JetCache提供了比SpringCache更强大的功能,包括支持TTL(Time To Live,生存时间)、两级缓存、分布式自动刷新等特性。它支持多种缓存实现,如RedisCache、CaffeineCache(内存缓存)和LinkedHashMapCache(内存缓存),并且可以轻松添加新的缓存实现。
JetCache支持的缓存类型
- 本地缓存类型:LinkedHashMapCache和CaffeineCache
- 远程缓存类型:Redis、Tair等
JetCache的核心优势
- 统一的API:提供一致的缓存操作接口
- 多级缓存:支持本地+远程的两级缓存架构
- TTL支持:灵活的过期时间设置
- 自动刷新:支持缓存的自动刷新机制
- 缓存一致性:保证分布式环境下的缓存一致性
- 丰富的注解:简化缓存的使用
项目依赖配置
Maven依赖
xml
<dependencies>
<!-- SpringBoot3 Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JetCache核心依赖 -->
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis-lettuce</artifactId>
<version>2.7.3</version>
</dependency>
<!-- Redis依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
配置文件
application.yml配置
yaml
jetcache:
## 统计间隔,0表示不统计,开启后定期在控制台输出缓存信息
statIntervalMinutes: 15
## 是否把areaCacheName作为远程缓存key前缀 如果注解上没有指定area默认值是default
areaInCacheName: false
## 本地缓存配置
local:
default: ## default表示全部生效,也可以指定某个cacheName
## 本地缓存类型,其他可选:caffeine/linkedhashmap
type: caffeine
keyConvertor: jackson
#expireAfterWrite: 1800s # 缓存写入后30分钟过期
# lettuce远程缓存配置
remote:
default:
type: redis.lettuce
keyConvertor: jackson
broadcastChannel: ${spring.application.name}
mode: single # 单机模式(默认值,可省略)
# 有密码 uri格式:redis://密码@ip:端口/redis库名?timeout=5s
uri: redis://127.0.0.1:6379/ # 单机Redis地址
spring:
redis:
host: 127.0.0.1
port: 6379
application:
name: jetcache-demo
实体类定义
java
package com.example.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 用户实体类
* 注意:缓存的对象必须实现Serializable接口
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 1L; // 序列化版本号
private Long id; // 用户ID
private String name; // 用户名
private Integer age; // 年龄
private Integer sex; // 性别(1-男,2-女,0-未知)
}
控制器实现
java
package com.example.controller;
import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.example.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* JetCache缓存演示控制器
*/
@RestController
public class JetcacheController {
/**
* 使用本地和远程缓存(两级缓存)
* @param id 用户ID
* @return 用户信息
*/
@GetMapping("/article/getBoth/{id}")
@Cached(name="userCache:", key = "#id", expire = 3600, localExpire = 3500, cacheType = CacheType.BOTH)
public User getBoth(@PathVariable Long id){
// 直接新建用户,模拟从数据库获取数据
User user = new User();
user.setId(id);
user.setName("用户both"+id);
user.setAge(23);
user.setSex(1);
System.out.println("第一次获取数据,未走缓存:"+id);
return user;
}
/**
* 删除缓存
* @param id 用户ID
* @return 删除结果
*/
@GetMapping("/article/deleteUser/{id}")
@CacheInvalidate(name = "userCache:", key = "#id")
public Boolean deleteUser(@PathVariable Long id) {
System.out.println("删除缓存:"+id);
// TODO 从数据库删除
return true;
}
}
核心注解详解
@Cached注解
@Cached是JetCache最核心的注解,用于标记需要缓存的方法。
主要参数:
- name: 缓存名称,作为缓存key的前缀
- key: 缓存key的表达式,支持SpEL表达式
- expire: 远程缓存过期时间(秒)
- localExpire: 本地缓存过期时间(秒)
- cacheType : 缓存类型
CacheType.LOCAL: 仅使用本地缓存CacheType.REMOTE: 仅使用远程缓存CacheType.BOTH: 使用两级缓存(本地+远程)
- condition: 缓存条件,支持SpEL表达式
- unless: 排除条件,支持SpEL表达式
使用示例:
java
// 基本用法
@Cached(name = "userCache:", key = "#id", expire = 3600)
public User getUser(Long id) { ... }
// 两级缓存
@Cached(name = "userCache:", key = "#id", expire = 3600, localExpire = 1800, cacheType = CacheType.BOTH)
public User getUserWithBothCache(Long id) { ... }
// 条件缓存
@Cached(name = "userCache:", key = "#id", expire = 3600, condition = "#id > 0")
public User getUserWithCondition(Long id) { ... }
// 排除条件
@Cached(name = "userCache:", key = "#id", expire = 3600, unless = "#result == null")
public User getUserUnlessNull(Long id) { ... }
@CacheInvalidate注解
@CacheInvalidate用于删除缓存。
主要参数:
- name: 缓存名称
- key: 要删除的缓存key
- condition: 删除条件
使用示例:
java
// 删除指定key的缓存
@CacheInvalidate(name = "userCache:", key = "#id")
public void deleteUser(Long id) { ... }
// 条件删除
@CacheInvalidate(name = "userCache:", key = "#id", condition = "#id > 0")
public void deleteUserWithCondition(Long id) { ... }
@CacheUpdate注解
@CacheUpdate用于更新缓存。
java
@CacheUpdate(name = "userCache:", key = "#user.id", value = "#user")
public void updateUser(User user) {
// 更新数据库
userRepository.save(user);
}
@CacheRefresh注解
@CacheRefresh用于自动刷新缓存。
java
@Cached(name = "userCache:", key = "#id", expire = 3600)
@CacheRefresh(refresh = 1800) // 30分钟后自动刷新
public User getUserWithRefresh(Long id) { ... }
启动类配置
java
package com.example;
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SpringBoot启动类
*/
@SpringBootApplication
@EnableMethodCache(basePackages = "com.example") // 启用方法缓存
@EnableCreateCacheAnnotation // 启用@CreateCache注解
public class JetCacheApplication {
public static void main(String[] args) {
SpringApplication.run(JetCacheApplication.class, args);
}
}
启动注解说明
- @EnableMethodCache : 启用方法级别的缓存注解支持
basePackages: 指定扫描的包路径
- @EnableCreateCacheAnnotation: 启用@CreateCache注解支持
测试验证
创建测试接口验证缓存效果:
bash
# 第一次访问,会查询数据库
curl http://localhost:8080/article/getBoth/1
# 第二次访问,走缓存
curl http://localhost:8080/article/getBoth/1
# 删除缓存
curl http://localhost:8080/article/deleteUser/1
# 再次访问,重新查询数据库
curl http://localhost:8080/article/getBoth/1