Spring Boot 整合 Redis

以下是 Spring Boot 整合 Redis 的指南,涵盖配置、基本操作、高级用法及常见问题解决。


1. 添加依赖

pom.xml 中添加 Spring Data Redis 和连接池依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 如果需要使用 Lettuce 连接池 -->
<dependency>
    <groupId>io.lettuce</groupId>
    <artifactId>lettuce-core</artifactId>
</dependency>

2. 配置 Redis

application.yml 中配置 Redis 连接信息:

yaml 复制代码
spring:
  redis:
    host: localhost
    port: 6379
    password: your_password  # 无密码则留空
    database: 0
    timeout: 5000ms
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 2
        max-wait: 1000ms

3. 配置 RedisTemplate(关键步骤)

默认的 RedisTemplate 使用 JDK 序列化,建议自定义为 JSON 序列化:

java 复制代码
@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(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        
        // Value 使用 JSON 序列化(支持复杂对象)
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        return template;
    }
}

4. 基本操作示例

存储与读取数据
java 复制代码
@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 存储字符串
    public void setString(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 存储对象
    public void setObject(String key, Object obj) {
        redisTemplate.opsForValue().set(key, obj);
    }

    // 获取数据
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // 删除数据
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    // 设置过期时间(秒)
    public Boolean expire(String key, long timeout) {
        return redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }
}

5. 高级用法

5.1 事务管理
java 复制代码
public void executeWithTransaction() {
    redisTemplate.multi(); // 开启事务
    try {
        redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForList().leftPush("list", "item1");
        redisTemplate.exec(); // 提交事务
    } catch (Exception e) {
        redisTemplate.discard(); // 回滚事务
    }
}
5.2 发布/订阅(Pub/Sub)

订阅者:

java 复制代码
@Component
public class RedisMessageListener implements MessageListener {
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel());
        String body = new String(message.getBody());
        System.out.println("Received: " + body + " from channel: " + channel);
    }
}

发布消息:

java 复制代码
@Service
public class RedisPublisher {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void publish(String channel, String message) {
        redisTemplate.convertAndSend(channel, message);
    }
}
5.3 集成 Spring Cache

启用缓存:

java 复制代码
@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

使用缓存注解:

java 复制代码
@Service
public class UserService {
    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) {
        // 模拟数据库查询
        return new User(id, "Alice");
    }

    @CacheEvict(value = "users", key = "#id")
    public void deleteUser(Long id) {
        // 删除用户逻辑
    }
}

6. 处理常见问题

6.1 序列化问题
  • 现象:Redis 中存储的数据为乱码。
  • 解决方案 :自定义 RedisTemplate 的序列化器(如上述 JSON 配置)。
6.2 连接池配置
  • 问题:连接数不足或泄漏。
  • 解决方案 :根据业务调整 max-activemax-idle,确保合理释放连接。
6.3 Redis 集群配置

application.yml 中配置集群节点:

yaml 复制代码
spring:
  redis:
    cluster:
      nodes: 192.168.1.101:6379,192.168.1.102:6379,192.168.1.103:6379
    lettuce:
      pool:
        max-active: 16

7. 完整代码示例

实体类
java 复制代码
public class User {
    private Long id;
    private String name;
    // 省略构造函数、Getter/Setter
}
Controller 层
java 复制代码
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisService redisService;

    @GetMapping("/set")
    public String setValue(@RequestParam String key, @RequestParam String value) {
        redisService.setString(key, value);
        return "Set success";
    }

    @GetMapping("/get")
    public Object getValue(@RequestParam String key) {
        return redisService.get(key);
    }
}

8. 测试与验证

  1. 启动 Redis 服务。

  2. 运行 Spring Boot 应用。

  3. 使用 curl 或 Postman 测试接口:

    bash 复制代码
    curl "http://localhost:8080/redis/set?key=name&value=Alice"
    curl "http://localhost:8080/redis/get?key=name"

总结

通过以上步骤,你可以实现:

  • 基础操作:字符串、对象的存储与读取。
  • 高级功能:事务、发布/订阅、缓存注解。
  • 优化配置:连接池、序列化、集群支持。

根据业务需求选择合适的 Redis 客户端(Lettuce/Jedis)和序列化方式,确保高性能与兼容性。

相关推荐
初次攀爬者12 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺12 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart13 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
Nyarlathotep011319 小时前
SpringBoot Starter的用法以及原理
java·spring boot
dkbnull2 天前
深入理解Spring两大特性:IoC和AOP
spring boot
洋洋技术笔记2 天前
Spring Boot条件注解详解
java·spring boot
洋洋技术笔记3 天前
Spring Boot配置管理最佳实践
spring boot
用户8307196840824 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
大道至简Edward4 天前
Spring Boot 2.7 + JDK 8 升级到 Spring Boot 3.x + JDK 17 完整指南
spring boot·后端
洋洋技术笔记4 天前
Spring Boot启动流程解析
spring boot·后端