SpringBoot 集成JetCache

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 支持、缓存预热等)。

### 如何在 Spring Boot 3 中集成 JetCache 为了在 Spring Boot 3 中成功集成 JetCache 并实现缓存功能,可以按照以下方式完成配置: #### 配置 Maven 或 Gradle 依赖项 首先,在项目的 `pom.xml` 文件中引入必要的 JetCacheSpring Boot 缓存支持的相关依赖项。以下是基于 Maven 的示例配置[^4]: ```xml <dependency> <groupId>com.alicloud.openservices</groupId> <artifactId>jetcache-starter-redis-spring-boot3</artifactId> <version>3.0.0</version> <!-- 版本号需根据实际需求调整 --> </dependency> <!-- 如果使用 Redis,则需要额外添加 Redis 客户端驱动 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 对于 Gradle 用户,可采用如下形式: ```gradle implementation 'com.alicloud.openservices:jetcache-starter-redis-spring-boot3:3.0.0' implementation 'org.springframework.boot:spring-boot-starter-data-redis' ``` #### 添加 JetCache 配置文件 创建或修改 `application.yml` 文件以定义 JetCache 的具体参数设置。例如: ```yaml jetcache: statIntervalMinutes: 15 areaInBytes: true local: default: type: caffeine keyConvertPolicy: hashcode limit: 1000 remote: default: type: redis poolConfig: minIdle: 5 maxIdle: 10 maxTotal: 20 cacheNullValue: false expireAfterWriteMillis: 600000 ``` 上述配置指定了本地缓存(Caffeine)和远程缓存(Redis),并设置了相应的过期时间和其他属性。 #### 使用注解启用缓存功能 通过在类上标注 `@EnableCaching` 启用 Spring Cache 功能,并利用 JetCache 提供的自定义注解来管理缓存逻辑。例如: ```java import com.alicloud.ttl.JetCacheAnnotationSupport; import org.springframework.cache.annotation.EnableCaching; @EnableCaching @JetCacheAnnotationSupport public class MyService { @Cached(name = "itemCache", localExpire = 60, remoteExpire = 300) public String getItemById(String id) { // 实际查询数据库或其他数据源的操作 return fetchItemFromDatabase(id); } private String fetchItemFromDatabase(String id) { // 数据获取逻辑省略... return "Item-" + id; } } ``` 以上代码片段展示了如何声明一个带有默认命名空间 (`name`) 及其对应的本地与远端失效策略的方法级缓存操作。 #### 测试环境准备 如果尚未初始化项目结构,请先执行以下命令克隆官方样例工程作为起点[^3]: ```bash git clone -b start https://github.com/oktadeveloper/okta-spring-boot-jpa-example.git cd okta-spring-boot-jpa-example/backend/ mvn clean install ``` 最后运行应用程序验证一切正常工作即可。 --- 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值