IntelliJ IDEA中Spring Boot 3.4.x+集成Redis 7.x:最新配置与实战指南

‌前言

Spring Boot 3.4.x作为当前‌最新稳定版本‌ ,全面支持Java 17+与Jakarta EE 10规范。本文以‌Spring Boot 3.4.1‌ 和‌Redis 7.x‌ 为例,详解如何在IDEA中快速接入Redis,涵盖‌最新依赖配置‌、‌数据序列化优化‌、‌缓存注解‌ 及‌高版本常见问题排查‌,助你掌握企业级缓存方案!


‌一、环境要求

1. ‌基础环境

  • JDK 17+(推荐OpenJDK 17/21)
  • IntelliJ IDEA 2023.1+
  • Redis 7.x(官网下载

2. ‌项目初始化

  • 使用Spring Initializr创建项目,选择:
    • Spring Boot 3.4.x
    • 依赖项:Spring Web, Spring Data Redis, Lombok

二、依赖配置(Spring Boot 3.4.x+特性)

‌1. pom.xml关键依赖

bash 复制代码
<!-- Spring Boot 3.4.x 父工程 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.4.1</version>
</parent>

<!-- Redis Starter(默认Lettuce) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- Jakarta JSON处理(兼容Redis序列化) -->
<dependency>
    <groupId>jakarta.json</groupId>
    <artifactId>jakarta.json-api</artifactId>
    <version>2.1.2</version>
</dependency>
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>jakarta.json</artifactId>
    <version>2.0.1</version>
</dependency>

‌注‌:Spring Boot 3.4.x默认使用‌Lettuce 6.3.x‌,无需额外配置连接池。若需Jedis,需手动排除Lettuce并添加Jedis依赖。


‌三、Redis连接配置

1. application.yml(推荐格式)

bash 复制代码
spring:
  data:
    redis:
      host: localhost
      port: 6379
      password: # 无密码留空
      database: 0
      lettuce:
        pool:
          max-active: 8
          max-idle: 4
          min-idle: 0
          max-wait: 2000ms
      # 新版本支持客户端名称(监控识别)
      client-name: springboot-app

‌2. 自定义序列化(解决Jackson兼容性问题)

bash 复制代码
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        
        // Key使用String序列化
        template.setKeySerializer(RedisSerializer.string());
        // Value使用JSON序列化(适配Jakarta)
        template.setValueSerializer(buildJsonSerializer());
        
        return template;
    }

    private RedisSerializer<Object> buildJsonSerializer() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.activateDefaultTyping(
            mapper.getPolymorphicTypeValidator(),
            ObjectMapper.DefaultTyping.EVERYTHING,
            JsonTypeInfo.As.PROPERTY
        );
        return new GenericJackson2JsonRedisSerializer(mapper);
    }
}

‌四、缓存注解实战(适配Spring 6.x+)

‌1. 启用缓存

bash 复制代码
@SpringBootApplication
@EnableCaching
public class DemoApplication { ... }

‌2. 服务层缓存示例

bash 复制代码
@Service
@CacheConfig(cacheNames = "userCache")
public class UserService {

    @Autowired
    private UserRepository repository;

    // 使用SpEL动态生成Key
    @Cacheable(key = "#id + '_' + #type")
    public User getUser(Long id, String type) {
        return repository.findById(id).orElseThrow();
    }

    // 条件缓存(仅缓存长度>5的名称)
    @Cacheable(key = "#name", condition = "#name.length() > 5")
    public User getUserByName(String name) {
        return repository.findByName(name);
    }

    // 事务性缓存更新(结合@Transactional)
    @Transactional
    @CachePut(key = "#user.id")
    public User updateUser(@NonNull User user) {
        return repository.save(user);
    }
}

‌五、响应式Redis操作(可选)

‌1. 添加响应式依赖

bash 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>

‌2. 响应式模板使用

bash 复制代码
@Autowired
private ReactiveRedisTemplate<String, Object> reactiveTemplate;

public Mono<Boolean> saveSession(String sessionId, User user) {
    return reactiveTemplate.opsForValue()
            .set("session:" + sessionId, user, Duration.ofMinutes(30));
}

‌六、常见问题与解决方案

‌Q1:Jackson序列化失败(Jakarta兼容性问题)

  • 现象‌InvalidTypeIdException: Missing type id when trying to resolve subtype
  • 解决‌
    1. 确认添加了jakarta.json依赖。
    2. RedisConfig中显式配置ObjectMapper(参考上文)。

‌Q2:Redis连接池不生效

  • 原因‌:Spring Boot 3.4.x默认启用Lettuce连接池,无需额外配置。
  • 验证‌ :通过/actuator/metrics/redis.pool.active端点监控连接状态。

‌Q3:Spring Boot 3.4.x与Redis 7.x的TLS连接

  • 配置‌
bash 复制代码
spring:
  data:
    redis:
      url: rediss://localhost:6379  # SSL协议
      ssl: true
      client-type: lettuce
      lettuce:
        pool:
          enabled: true
        ssl:
          key-store-type: PKCS12
          key-store: classpath:keystore.p12
          key-store-password: 123456

总结

Spring Boot 3.4.x在Redis集成上进一步优化了性能与兼容性,支持最新的Jakarta标准和响应式编程。本文从‌依赖配置‌到‌高级特性‌,提供了一套完整的生产级解决方案。

相关推荐
麦兜*3 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了4 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
大只鹅4 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
天河归来4 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
IT_10244 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
武昌库里写JAVA5 小时前
Oracle如何使用序列 Oracle序列使用教程
java·开发语言·spring boot·学习·课程设计
超级小忍6 小时前
Spring Boot 中常用的工具类库及其使用示例(完整版)
spring boot·后端
程序员张36 小时前
SQL分析与打印-p6spy组件
spring boot·sql·mybatis·mybatisplus·p6spy
CHENWENFEIc6 小时前
SpringBoot论坛系统安全测试实战报告
spring boot·后端·程序人生·spring·系统安全·安全测试
爱上语文8 小时前
Redis基础(6):SpringDataRedis
数据库·redis·后端