赞
踩
以下是一个Spring Boot应用程序集成Redis的示例,展示了如何存储和查询数据。我们将使用Spring Data Redis模块来实现这个示例。
首先,确保你在项目的pom.xml
文件中添加了以下依赖:
- <dependencies>
- <!-- Spring Boot Starter Data Redis -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- <version>2.3.12.RELEASE</version>
- </dependency>
-
- <!-- Spring Boot Starter Web -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- <version>2.3.12.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-pool2</artifactId>
- <version>2.11.1</version>
- </dependency>
- </dependencies>
在项目的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
创建一个简单的实体类:
-
- package com.example.redisdemo.model;
-
- import java.io.Serializable;
-
- public class User implements Serializable {
-
- private String id;
- private String name;
- private int age;
-
- // Getters and setters
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
- }
-
创建一个配置类来定义RedisTemplate:
- package com.example.redisdemo.config;
-
-
- import com.fasterxml.jackson.annotation.JsonAutoDetect;
- import com.fasterxml.jackson.annotation.PropertyAccessor;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.connection.RedisConnectionFactory;
- import org.springframework.data.redis.connection.RedisPassword;
- import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
- import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
- import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
- import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
- import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
-
- import java.time.Duration;
-
- @Configuration
- public class RedisConfig {
- @Value("${spring.redis.database}")
- private int database;
-
- @Value("${spring.redis.host}")
- private String host;
-
- @Value("${spring.redis.password}")
- private String password;
-
- @Value("${spring.redis.port}")
- private int port;
-
- @Value("${spring.redis.timeout}")
- private long timeout;
-
- @Value("${spring.redis.lettuce.pool.max-idle}")
- private int maxIdle;
-
- @Value("${spring.redis.lettuce.pool.min-idle}")
- private int minIdle;
-
- @Value("${spring.redis.lettuce.pool.max-active}")
- private int maxActive;
-
- @Value("${spring.redis.lettuce.pool.max-wait}")
- private long maxWait;
-
- Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
-
- @Bean
- public LettuceConnectionFactory redisConnectionFactory() {
- GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
- genericObjectPoolConfig.setMaxIdle(maxIdle);
- genericObjectPoolConfig.setMinIdle(minIdle);
- genericObjectPoolConfig.setMaxTotal(maxActive);
- genericObjectPoolConfig.setMaxWaitMillis(maxWait);
- genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis(100);
- RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
- redisStandaloneConfiguration.setDatabase(database);
- redisStandaloneConfiguration.setHostName(host);
- redisStandaloneConfiguration.setPort(port);
- redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
- LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
- .commandTimeout(Duration.ofMillis(timeout))
- .poolConfig(genericObjectPoolConfig)
- .build();
-
- LettuceConnectionFactory factory = new LettuceConnectionFactory(redisStandaloneConfiguration, clientConfig);
- return factory;
- }
-
- @Bean
- public RedisTemplate<String, Object> redisTemplate() {
- RedisTemplate<String, Object> template = new RedisTemplate<>();
- template.setConnectionFactory(redisConnectionFactory());
- template.setKeySerializer(new StringRedisSerializer());
- template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
- return template;
- }
- }
-
创建一个服务层来封装业务逻辑:
- package com.example.redisdemo.service;
-
-
- import com.example.redisdemo.model.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.stereotype.Service;
-
- import java.util.concurrent.TimeUnit;
-
- @Service
- public class UserService {
-
- private static final String USER_KEY_PREFIX = "user:";
-
- @Autowired
- private RedisTemplate<String, Object> redisTemplate;
-
- public void saveUser(User user) {
- redisTemplate.opsForValue().set(USER_KEY_PREFIX + user.getId(), user, 10, TimeUnit.MINUTES);
- }
-
- public User getUser(String id) {
- return (User) redisTemplate.opsForValue().get(USER_KEY_PREFIX + id);
- }
-
- public void deleteUser(String id) {
- redisTemplate.delete(USER_KEY_PREFIX + id);
- }
- }
-
创建一个控制器来处理HTTP请求:
- package com.example.redisdemo.controller;
-
-
- import com.example.redisdemo.model.User;
- import com.example.redisdemo.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.*;
-
- @RestController
- @RequestMapping("/users")
- public class UserController {
-
- @Autowired
- private UserService userService;
-
- @PostMapping
- public String saveUser(@RequestBody User user) {
- userService.saveUser(user);
- return "User saved successfully!";
- }
-
- @GetMapping("/{id}")
- public User getUser(@PathVariable String id) {
- return userService.getUser(id);
- }
-
- @DeleteMapping("/{id}")
- public String deleteUser(@PathVariable String id) {
- userService.deleteUser(id);
- return "User deleted successfully!";
- }
- }
-
创建Spring Boot应用程序的主类:
- package com.example.redisdemo;
-
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
-
- @SpringBootApplication
- public class RedisDemoApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(RedisDemoApplication.class, args);
- }
- }
-
启动Spring Boot应用程序,确保Redis服务器正在运行。然后,你可以使用Postman或其他HTTP客户端来测试API:
存储数据:
- POST http://localhost:8080/users
- Body: { "id": "1", "name": "John", "age": 30 }
查询数据:
GET http://localhost:8080/users/1
删除数据:
DELETE http://localhost:8080/users/1
依赖管理:
配置:
application.yml
中指定Redis服务器的地址。配置类:
@Configuration
注解定义 RedisTemplate
,设置键和值的序列化方式。实体类:
User
类来表示存储的数据对象。服务层:
控制器:
通过这个示例,你可以轻松地使用Spring Boot集成Redis来实现数据的存储和查询功能。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。