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)和序列化方式,确保高性能与兼容性。

相关推荐
无名客09 分钟前
redis分布式锁为什么采用Lua脚本实现。而不是事务
redis·分布式·lua·事务
中国胖子风清扬31 分钟前
Rust 日志库完全指南:从入门到精通
spring boot·后端·rust·学习方法·logback
梦中的天之酒壶38 分钟前
Redis Stack扩展功能
数据库·redis·bootstrap
xiaogg36781 小时前
springboot rabbitmq 延时队列消息确认收货订单已完成
spring boot·rabbitmq·java-rabbitmq
麦兜*1 小时前
MongoDB 6.0 新特性解读:时间序列集合与加密查询
数据库·spring boot·mongodb·spring·spring cloud·系统架构
依稀i1232 小时前
Spring Boot + MySQL 创建超级管理员
spring boot·mysql
千里码aicood2 小时前
【springboot+vue】党员党建活动管理平台(源码+文档+调试+基础修改+答疑)
java·数据库·spring boot
Chan162 小时前
【智能协同云图库】基于统一接口架构构建多维度分析功能、结合 ECharts 可视化与权限校验实现用户 / 管理员图库统计、通过 SQL 优化与流式处理提升数据
java·spring boot·后端·sql·spring·intellij-idea·echarts
库库林_沙琪马2 小时前
REST接口幂等设计深度解析
spring boot·后端