当前位置:   article > 正文

如何使用Spring Boot框架整合Redis:超详细案例教程_spring-boot-starter-data-redis

spring-boot-starter-data-redis

目录

# 为什么选择Spring Boot与Redis整合?

1. 更新 pom.xml

2. 配置application.yml

3. 创建 Redis 配置类

4. Redis 操作类

5. 创建控制器

6. 启动应用程序

7. 测试


# 为什么选择Spring Boot与Redis整合?

将Spring Boot与Redis整合可以充分利用两者的优势,简化开发并提升应用性能。具体好处包括:

  1. 缓存支持:使用Redis作为缓存层可以极大提高应用的响应速度和可扩展性。
  2. 会话管理:将用户会话存储在Redis中,可以实现分布式会话管理。
  3. 数据持久性:Redis的持久化功能可以确保数据的可靠性。
  4. 简化配置:Spring Boot的自动配置和Redis Starter可以简化配置工作。

了解了这些基础知识后,接下来将详细介绍如何在Spring Boot项目中整合Redis,包括依赖配置、连接设置、基本操作和应用案例。

1. 更新 pom.xml

确保你的项目包含了以下依赖。如果使用 Spring Initializr 已经添加了 spring-boot-starter-data-redis,这里就无需再次添加。

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.commons</groupId>
  8. <artifactId>commons-pool2</artifactId>
  9. </dependency>
  10. </dependencies>

commons-pool2 是用于 Lettuce 连接池配置的依赖。

2. 配置application.yml

补充:

  • Spring Boot 1.x 和 Spring Boot 2.x 中,spring.redis.host 用于配置 Redis 连接属性。

  • Spring Boot 3.x 中,spring.redis.host 已经弃用。

  • Spring Boot 2.x 开始,引入了 spring.data.redis 作为配置 Redis 连接的方式,并且在 Spring Boot 3.x 中也可以使用 spring.data.redis 进行配置。

src/main/resources 目录下,添加 Redis 连接池的配置。

application.yml:

  1. server:
  2. port: 8080
  3. spring:
  4. redis:
  5. host: 127.0.0.1 # 地址
  6. port: 6379 # 端口号
  7. database: 0 # 数据库索引(默认为0)
  8. timeout: 1800000 # 连接超时时间(毫秒)
  9. lettuce:
  10. pool:
  11. max-active: 20 # 连接池最大连接数(使用负值表示没有限制)
  12. max-wait: -1 # 最大阻塞等待时间(负数表示没有限制)
  13. max-idle: 5 # 连接池中最大空闲连接
  14. min-idle: 0 # 连接池中最小空闲连接

3. 创建 Redis 配置类

com.lei.my_redis.config 包中创建或更新 RedisConfig 类,使用连接池配置 LettuceConnectionFactory

  1. package com.lei.my_redis.config;
  2. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
  3. import org.springframework.cache.annotation.CachingConfigurerSupport;
  4. import org.springframework.cache.annotation.EnableCaching;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
  8. import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
  9. import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import org.springframework.data.redis.serializer.StringRedisSerializer;
  12. @EnableCaching // 开启缓存
  13. @Configuration // 配置类
  14. public class RedisConfig extends CachingConfigurerSupport {
  15. /**
  16. * 配置 Redis 连接工厂
  17. * 意义: LettuceConnectionFactory 是连接 Redis 服务器的入口,它使用了 Lettuce 客户端,并且配置了连接池来提高性能和资源管理
  18. * @return LettuceConnectionFactory
  19. */
  20. @Bean
  21. public LettuceConnectionFactory redisConnectionFactory() {
  22. // 配置 Redis 服务器的连接信息
  23. RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
  24. redisStandaloneConfiguration.setHostName("localhost");
  25. redisStandaloneConfiguration.setPort(6379);
  26. // redisStandaloneConfiguration.setPassword("password"); // 取消注释以设置密码
  27. // 配置连接池
  28. GenericObjectPoolConfig<Object> poolConfig = new GenericObjectPoolConfig<>();
  29. poolConfig.setMaxTotal(10); // 连接池中的最大连接数
  30. poolConfig.setMaxIdle(5); // 连接池中的最大空闲连接数
  31. poolConfig.setMinIdle(1); // 连接池中的最小空闲连接数
  32. poolConfig.setMaxWaitMillis(2000); // 连接池获取连接的最大等待时间
  33. // 创建一个带有连接池配置的 Lettuce 客户端配置
  34. LettucePoolingClientConfiguration lettucePoolingClientConfiguration =
  35. LettucePoolingClientConfiguration.builder()
  36. .poolConfig(poolConfig)
  37. .build();
  38. // 返回带有连接池配置的 Redis 连接工厂
  39. return new LettuceConnectionFactory(redisStandaloneConfiguration, lettucePoolingClientConfiguration);
  40. }
  41. /**
  42. * 配置并返回一个 RedisTemplate 实例,用于执行 Redis 操作
  43. * 意义: RedisTemplate 提供了一种高级抽象,使得开发者可以通过模板方法操作 Redis,而无需直接处理底层的 Redis 命令。
  44. * 它支持多种 Redis 操作,例如值操作、哈希操作、列表操作等
  45. * @return RedisTemplate
  46. */
  47. @Bean
  48. public RedisTemplate<String, Object> redisTemplate() {
  49. /*
  50. 1.创建 RedisTemplate: 这是 Spring 用于与 Redis 交互的核心类,简化了与 Redis 的交互。
  51. 2.设置连接工厂: 使用前面定义的 LettuceConnectionFactory。
  52. 3.设置序列化器: 设置键和值的序列化器,这里使用 StringRedisSerializer 来将键和值序列化为字符串。
  53. */
  54. RedisTemplate<String, Object> template = new RedisTemplate<>();
  55. template.setConnectionFactory(redisConnectionFactory()); // 设置连接工厂
  56. template.setKeySerializer(new StringRedisSerializer()); // 设置键的序列化器
  57. template.setValueSerializer(new StringRedisSerializer()); // 设置值的序列化器
  58. return template;
  59. }
  60. }

4. Redis 操作类

保持 Redis 操作类和控制器不变。它们已经实现了基本的 Redis 操作。这里只需更新 RedisService 类以支持连接池即可。

  1. package com.lei.my_redis.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.stereotype.Service;
  5. import java.util.concurrent.TimeUnit;
  6. /**
  7. * RedisService 类提供了简化的 Redis 操作接口,用于在 Spring Boot 应用中存储和检索数据。
  8. * 它通过 RedisTemplate 与 Redis 服务器交互,执行常见的操作如设置值、获取值、设置值带过期时间和删除值。
  9. */
  10. @Service
  11. public class RedisService {
  12. /*
  13. 意义: RedisTemplate 是 Spring 提供的一个 Redis 操作模板,它抽象了 Redis 的底层访问,
  14. 使开发者可以用 Java 对象操作 Redis。使用 @Autowired 注解,Spring 自动将配置好的 RedisTemplate 注入到 RedisService 类中
  15. */
  16. @Autowired
  17. private RedisTemplate<String, Object> redisTemplate;
  18. // 作用: 向 Redis 中存储一个键值对
  19. public void setValue(String key, Object value) {
  20. redisTemplate.opsForValue().set(key, value);
  21. }
  22. // 作用: 从 Redis 中获取指定键的值
  23. public Object getValue(String key) {
  24. return redisTemplate.opsForValue().get(key);
  25. }
  26. // 作用: 向 Redis 中存储一个键值对,并设置其过期时间
  27. // timeout 指定时间量,timeUnit 指定时间单位
  28. public void setValueWithExpiry(String key, Object value, long timeout, TimeUnit timeUnit) {
  29. redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
  30. }
  31. // 作用: 从 Redis 中删除指定键及其对应的值
  32. public void deleteValue(String key) {
  33. redisTemplate.delete(key);
  34. }
  35. }

5. 创建控制器

RedisController 类的实现保持不变。

  1. package com.lei.my_redis.controller;
  2. import com.lei.my_redis.service.RedisService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.PostMapping;
  6. import org.springframework.web.bind.annotation.RequestParam;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * RedisController 是一个 REST 控制器类,用于处理客户端发来的 HTTP 请求,并通过调用 RedisService
  10. * 执行 Redis 数据操作。它提供了三个 API 端点:设置值、获取值和删除值
  11. * RestController注解作用: 表示这个类是一个 RESTful 控制器,它的所有方法的返回值都会直接作为 HTTP 响应体返回。
  12. * RestController注解意义: 结合 @Controller@ResponseBody 的功能,简化了返回 JSON 格式数据的开发工作。
  13. */
  14. @RestController
  15. public class RedisController {
  16. @Autowired
  17. private RedisService redisService;
  18. /**
  19. * 作用: 处理 HTTP POST 请求,设置 Redis 中的键值对
  20. * 1.使用 @RequestParam 注解获取请求参数 key 和 value
  21. * 2.调用 redisService.setValue(key, value) 方法,将 key 和 value 存储到 Redis 中
  22. * 3.返回一个简单的字符串 "Value set" 作为响应
  23. * 请求:POST /set?key=myKey&value=myValue
  24. * 响应:"Value set"
  25. * RequestParam注解:获取请求参数: 它从 HTTP 请求中获取参数,并将这些参数绑定到控制器方法的参数上
  26. */
  27. // @PostMapping("/set")
  28. @GetMapping("/set")
  29. public String setValue(@RequestParam String key, @RequestParam String value) {
  30. redisService.setValue(key, value);
  31. return "Value:(" + key + ") set";
  32. }
  33. /**
  34. * 作用: 处理 HTTP GET 请求,从 Redis 中获取指定键的值
  35. * 1.使用 @RequestParam 注解获取请求参数 key
  36. * 2.调用 redisService.getValue(key) 方法,从 Redis 中获取 key 对应的值,并将结果转换为 String 类型
  37. * 3.返回获取的值
  38. * 请求:GET /get?key=myKey
  39. * 响应:"myValue" // Redis 中对应 `myKey` 的值
  40. */
  41. @GetMapping("/get")
  42. public String getValue(@RequestParam String key) {
  43. return (String) redisService.getValue(key);
  44. }
  45. /**
  46. * 作用: 处理 HTTP POST 请求,删除 Redis 中指定键的值
  47. * 1.使用 @RequestParam 注解获取请求参数 key
  48. * 2.调用 redisService.deleteValue(key) 方法,从 Redis 中删除 key 对应的键值对
  49. * 3.返回一个简单的字符串 "Value deleted" 作为响应
  50. * 请求:POST /delete?key=myKey
  51. * 响应:"Value deleted"
  52. */
  53. // @PostMapping("/delete")
  54. @GetMapping("/delete")
  55. public String deleteValue(@RequestParam String key) {
  56. redisService.deleteValue(key);
  57. return "Value:(" + key + ") deleted";
  58. }
  59. }

6. 启动应用程序

SpringBootRedisApplication 主类保持不变。

  1. package com.lei.my_redis;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class MyRedisApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(MyRedisApplication.class, args);
  8. }
  9. }

7. 测试

启动应用程序后,可以选中通过 Postman 或浏览器访问以下 URL,验证 Redis 操作是否成功。

  • 设置值: POST http://localhost:8080/set?key=mykey&value=myvalue
  • 获取值: GET http://localhost:8080/get?key=mykey
  • 删除值: POST http://localhost:8080/delete?key=mykey

案例1:设置值

案例2:获取值

案例3:删除值

成功在 Spring Boot 项目中整合了 Redis 并配置了连接池。我们使用连接池可以显著提高 Redis 操作的性能和资源管理效率。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号