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 分钟前
【微服务】Nacos 配置动态刷新(简易版)(附配置)
java·spring boot·微服务
Evoxt 益沃斯1 小时前
Setup SSL/ HTTPS on NGINX on CentOS 8/ AlmaLinux 8/ RockyLinux 8
redis·网络协议·ssl
小蒜学长1 小时前
乡政府管理系统设计与实现(代码+数据库+LW)
数据库·spring boot·后端·学习·旅游
MiniFlyZt1 小时前
excel的导入和下载(poi)
spring boot·spring·excel
做想做的,2 小时前
el-table表格样式设置单元格样式方法 :cell-class-name
前端·javascript·vue.js·spring boot
程序媛学姐2 小时前
SpringBoot缓存抽象:@Cacheable与缓存管理器配置
java·spring boot·缓存
Nuyoahll-_-ll2 小时前
基于Redis实现限流
数据库·redis·缓存
小马爱打代码2 小时前
多级缓存架构实战:Caffeine+Redis
redis·缓存·架构
五月茶2 小时前
Redis
数据库·redis·缓存
学长论文辅导2 小时前
基于SpringBoot的校园二手交易平台(计算机毕设-JAVA)
java·spring boot·毕业设计·论文·管理系统·校园二手交易平台