当前位置:   article > 正文

Spring Boot应用程序集成Redis_spring-boot-starter-data-redis

spring-boot-starter-data-redis

以下是一个Spring Boot应用程序集成Redis的示例,展示了如何存储和查询数据。我们将使用Spring Data Redis模块来实现这个示例。

创建Spring Boot项目

首先,确保你在项目的pom.xml文件中添加了以下依赖:

  1. <dependencies>
  2. <!-- Spring Boot Starter Data Redis -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-data-redis</artifactId>
  6. <version>2.3.12.RELEASE</version>
  7. </dependency>
  8. <!-- Spring Boot Starter Web -->
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-web</artifactId>
  12. <version>2.3.12.RELEASE</version>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.apache.commons</groupId>
  16. <artifactId>commons-pool2</artifactId>
  17. <version>2.11.1</version>
  18. </dependency>
  19. </dependencies>

配置Redis

在项目的application.yml文件中添加Redis相关的配置:

spring:
  redis:
    database: 0
    # 地址
    host: 127.0.0.1
    # 端口,默认为6379
    port: 6379
    # 密码
    password:
    # 连接超时时间 ms
    timeout: 10000
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 1
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池的最大数据库连接数
        max-active: 8
        # #连接池最大阻塞等待时间(使用负值表示没有限制) ms
        max-wait: -1

创建实体类

创建一个简单的实体类:

  1. package com.example.redisdemo.model;
  2. import java.io.Serializable;
  3. public class User implements Serializable {
  4. private String id;
  5. private String name;
  6. private int age;
  7. // Getters and setters
  8. public String getId() {
  9. return id;
  10. }
  11. public void setId(String id) {
  12. this.id = id;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public int getAge() {
  21. return age;
  22. }
  23. public void setAge(int age) {
  24. this.age = age;
  25. }
  26. }

创建配置类

创建一个配置类来定义RedisTemplate:

  1. package com.example.redisdemo.config;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.data.redis.connection.RedisConnectionFactory;
  10. import org.springframework.data.redis.connection.RedisPassword;
  11. import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
  12. import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
  13. import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
  14. import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
  15. import org.springframework.data.redis.core.RedisTemplate;
  16. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  17. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  18. import org.springframework.data.redis.serializer.StringRedisSerializer;
  19. import java.time.Duration;
  20. @Configuration
  21. public class RedisConfig {
  22. @Value("${spring.redis.database}")
  23. private int database;
  24. @Value("${spring.redis.host}")
  25. private String host;
  26. @Value("${spring.redis.password}")
  27. private String password;
  28. @Value("${spring.redis.port}")
  29. private int port;
  30. @Value("${spring.redis.timeout}")
  31. private long timeout;
  32. @Value("${spring.redis.lettuce.pool.max-idle}")
  33. private int maxIdle;
  34. @Value("${spring.redis.lettuce.pool.min-idle}")
  35. private int minIdle;
  36. @Value("${spring.redis.lettuce.pool.max-active}")
  37. private int maxActive;
  38. @Value("${spring.redis.lettuce.pool.max-wait}")
  39. private long maxWait;
  40. Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
  41. @Bean
  42. public LettuceConnectionFactory redisConnectionFactory() {
  43. GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
  44. genericObjectPoolConfig.setMaxIdle(maxIdle);
  45. genericObjectPoolConfig.setMinIdle(minIdle);
  46. genericObjectPoolConfig.setMaxTotal(maxActive);
  47. genericObjectPoolConfig.setMaxWaitMillis(maxWait);
  48. genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis(100);
  49. RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
  50. redisStandaloneConfiguration.setDatabase(database);
  51. redisStandaloneConfiguration.setHostName(host);
  52. redisStandaloneConfiguration.setPort(port);
  53. redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
  54. LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
  55. .commandTimeout(Duration.ofMillis(timeout))
  56. .poolConfig(genericObjectPoolConfig)
  57. .build();
  58. LettuceConnectionFactory factory = new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
  59. return factory;
  60. }
  61. @Bean
  62. public RedisTemplate<String, Object> redisTemplate() {
  63. RedisTemplate<String, Object> template = new RedisTemplate<>();
  64. template.setConnectionFactory(redisConnectionFactory());
  65. template.setKeySerializer(new StringRedisSerializer());
  66. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  67. return template;
  68. }
  69. }

创建服务层

创建一个服务层来封装业务逻辑:

  1. package com.example.redisdemo.service;
  2. import com.example.redisdemo.model.User;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.stereotype.Service;
  6. import java.util.concurrent.TimeUnit;
  7. @Service
  8. public class UserService {
  9. private static final String USER_KEY_PREFIX = "user:";
  10. @Autowired
  11. private RedisTemplate<String, Object> redisTemplate;
  12. public void saveUser(User user) {
  13. redisTemplate.opsForValue().set(USER_KEY_PREFIX + user.getId(), user, 10, TimeUnit.MINUTES);
  14. }
  15. public User getUser(String id) {
  16. return (User) redisTemplate.opsForValue().get(USER_KEY_PREFIX + id);
  17. }
  18. public void deleteUser(String id) {
  19. redisTemplate.delete(USER_KEY_PREFIX + id);
  20. }
  21. }

创建控制器

创建一个控制器来处理HTTP请求:

  1. package com.example.redisdemo.controller;
  2. import com.example.redisdemo.model.User;
  3. import com.example.redisdemo.service.UserService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.*;
  6. @RestController
  7. @RequestMapping("/users")
  8. public class UserController {
  9. @Autowired
  10. private UserService userService;
  11. @PostMapping
  12. public String saveUser(@RequestBody User user) {
  13. userService.saveUser(user);
  14. return "User saved successfully!";
  15. }
  16. @GetMapping("/{id}")
  17. public User getUser(@PathVariable String id) {
  18. return userService.getUser(id);
  19. }
  20. @DeleteMapping("/{id}")
  21. public String deleteUser(@PathVariable String id) {
  22. userService.deleteUser(id);
  23. return "User deleted successfully!";
  24. }
  25. }

Spring Boot 主类

创建Spring Boot应用程序的主类:

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

运行应用程序

启动Spring Boot应用程序,确保Redis服务器正在运行。然后,你可以使用Postman或其他HTTP客户端来测试API:

  • 存储数据

    1. POST http://localhost:8080/users
    2. Body: { "id": "1", "name": "John", "age": 30 }
  • 查询数据

    GET http://localhost:8080/users/1
  • 删除数据

    DELETE http://localhost:8080/users/1

解释

  1. 依赖管理

    • 使用Spring Boot Starter Data Redis来简化Redis集成。
    • 使用Spring Boot Starter Web来简化Web应用开发。
  2. 配置

    • application.yml中指定Redis服务器的地址。
  3. 配置类

    • 使用 @Configuration 注解定义 RedisTemplate ,设置键和值的序列化方式。
  4. 实体类

    • 创建一个简单的 User 类来表示存储的数据对象。
  5. 服务层

    • 封装业务逻辑,提供数据存储和查询的高层接口。
  6. 控制器

    • 处理HTTP请求,提供RESTful API进行数据存储和查询。

通过这个示例,你可以轻松地使用Spring Boot集成Redis来实现数据的存储和查询功能。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/890888
推荐阅读
相关标签
  

闽ICP备14008679号