前言
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关键依赖
<!-- 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(推荐格式)
spring:data:redis:host: localhostport: 6379password: # 无密码留空database: 0lettuce:pool:max-active: 8max-idle: 4min-idle: 0max-wait: 2000ms# 新版本支持客户端名称(监控识别)client-name: springboot-app
2. 自定义序列化(解决Jackson兼容性问题)
@Configuration
public class RedisConfig {@Beanpublic 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. 启用缓存
@SpringBootApplication
@EnableCaching
public class DemoApplication { ... }
2. 服务层缓存示例
@Service
@CacheConfig(cacheNames = "userCache")
public class UserService {@Autowiredprivate 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. 添加响应式依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
2. 响应式模板使用
@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
- 解决:
- 确认添加了
jakarta.json
依赖。 - 在
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连接
- 配置:
spring:data:redis:url: rediss://localhost:6379 # SSL协议ssl: trueclient-type: lettucelettuce:pool:enabled: truessl:key-store-type: PKCS12key-store: classpath:keystore.p12key-store-password: 123456
总结
Spring Boot 3.4.x在Redis集成上进一步优化了性能与兼容性,支持最新的Jakarta标准和响应式编程。本文从依赖配置到高级特性,提供了一套完整的生产级解决方案。