Spring Boot应用程序集成Redis

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

创建Spring Boot项目

首先,确保你在项目的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>

配置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

创建实体类

创建一个简单的实体类:


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 主类

创建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

解释

  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来实现数据的存储和查询功能。

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot集成Redis可以通过以下步骤实现: 1. 添加Redis依赖:在Spring Boot项目的pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息:在application.properties文件中添加以下配置信息: ``` spring.redis.host=redis服务器IP spring.redis.port=redis服务器端口号 spring.redis.password=redis密码 ``` 3. 创建RedisTemplate:在Java代码中创建RedisTemplate对象,并注入到需要使用Redis的类中。 ``` @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class)); redisTemplate.afterPropertiesSet(); return redisTemplate; } } ``` 4. 使用RedisTemplate操作Redis:通过RedisTemplate对象的方法,可以进行各种Redis操作,如set、get、delete等。 以上是Spring Boot集成Redis的基本步骤,具体实现还需根据具体需求进行配置和调整。 ### 回答2: Spring Boot是一个基于Spring框架的快速开发框架,它提供了简化的配置和开箱即用的功能,使得我们可以快速构建和部署应用程序。而Redis是一个高性能的键值对存储数据库,它常被用于缓存和数据存储。 在Spring Boot集成Redis,首先需要引入相关的依赖。可以通过Maven或Gradle来引入spring-boot-starter-data-redis依赖,该依赖会自动引入Redis相关的配置和依赖库。 然后,在配置文件中添加Redis的连接信息。在application.properties或application.yml中,可以配置Redis的主机地址、端口号、密码等信息。 接下来,在需要使用Redis的地方,可以使用@Autowired注解来注入RedisTemplate对象。RedisTemplate是Spring提供的操作Redis的模板类,它封装了常用的操作方法。 使用RedisTemplate,可以通过调用其对应的方法来操作Redis数据库,比如设置键值对、获取键值对、设置过期时间等。 除了RedisTemplate,Spring Boot还提供了RedisCacheManager类用于缓存管理,它可以通过注解@Configuration和@EnableCaching来启用缓存功能。在需要缓存的方法上使用@Cacheable注解,就可以将方法的返回值缓存到Redis中,下次调用时可以直接从缓存中获取,提高了性能。 总的来说,集成RedisSpring Boot中,只需要引入依赖、配置连接信息,然后通过RedisTemplate操作Redis数据库,或使用RedisCacheManager进行数据缓存管理就可以了。这样可以简化我们与Redis的交互,提高开发效率和应用性能。 ### 回答3: 在Spring Boot中,集成Redis可以通过以下步骤实现: 1. 在pom.xml文件中添加Redis的依赖库: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在application.properties或application.yaml文件中配置Redis连接信息: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= ``` 3. 创建一个Redis配置类,用于配置Redis连接工厂: ```java @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean @Override public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { // 生成缓存的key,可以根据实际需求定制 return ""; } }; } @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(connectionFactory); // 设置value的序列化方式 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // 设置key的序列化方式 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } } ``` 4. 在需要使用Redis的类中,通过注入RedisTemplate来操作Redis: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; public void cacheData(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object getData(String key) { return redisTemplate.opsForValue().get(key); } ``` 通过以上步骤,我们就成功在Spring Boot集成Redis,可以方便地使用Redis进行缓存、存储和读取数据。在配置Redis时,我们需要根据实际情况修改host、port和password等配置项。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值