嵌入式Redis服务器在Spring Boot测试中的使用教程

1、概述

Spring Data Redis提供了一种与Redis实例集成的简单方法。

但是,在某些情况下,使用嵌入式服务器比使用真实服务器创建开发和测试环境更方便。

因此,我们将学习如何设置和使用嵌入式Redis服务器。

2、依赖

让我们首先添加必要的依赖项:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
  <groupId>it.ozimov</groupId>
  <artifactId>embedded-redis</artifactId>
  <version>0.7.2</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

这个spring-boot-starter-test包含我们需要运行集成测试的各种依赖。

此外,embedded-redis包含我们将使用的嵌入式服务器。

3、设置

添加依赖项后,我们应该定义Redis服务器和我们的应用程序之间的连接设置。

让我们首先创建一个类来保存我们的属性:

@Configuration
public class RedisProperties {
    private int redisPort;
    private String redisHost;

    public RedisProperties(
      @Value("${spring.redis.port}") int redisPort,
      @Value("${spring.redis.host}") String redisHost) {
        this.redisPort = redisPort;
        this.redisHost = redisHost;
    }

    // getters
}

接下来,我们应该创建一个配置类来定义连接并使用我们的属性:

@Configuration
@EnableRedisRepositories
public class RedisConfiguration {

    @Bean
    public LettuceConnectionFactory redisConnectionFactory(
      RedisProperties redisProperties) {
        return new LettuceConnectionFactory(
          redisProperties.getRedisHost(),
          redisProperties.getRedisPort());
    }

    @Bean
    public RedisTemplate<?, ?> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        return template;
    }
}

配置非常简单。这样我们的嵌入式服务器可以在其他的端口上运行。

4、嵌入式Redis服务器

现在,我们将配置嵌入式服务器并在我们的一项测试中使用它。

首先,让我们在测试的资源目录(src/test/resources)中创建一个application.properties文件:

spring.redis.host=localhost
spring.redis.port=6370

之后,我们将创建一个@TestConfiguration注解的配置类:

@TestConfiguration
public class TestRedisConfiguration {

    private RedisServer redisServer;

    public TestRedisConfiguration(RedisProperties redisProperties) {
        this.redisServer = new RedisServer(redisProperties.getRedisPort());
    }

    @PostConstruct
    public void postConstruct() {
        redisServer.start();
    }

    @PreDestroy
    public void preDestroy() {
        redisServer.stop();
    }
}

当context上下文启动,服务器就跟着启动。它根据我们在属性中定义的端口运行在我们的机器上。有了它,我们现在可以在不停止实际Redis服务器的情况下运行测试了。

理想情况下,我们希望在随机可用端口上启动它,但嵌入式Redis尚不具备此功能。我们现在可以做的是通过ServerSocket API 获取随机端口。

此外,当上下文停止,服务器也跟着停止。

服务器也可以由我们自己的可执行文件来提供:

this.redisServer = new RedisServer("/path/redis", redisProperties.getRedisPort());

此外,可执行文件可以按不同的操作系统来定义:

RedisExecProvider customProvider = RedisExecProvider.defaultProvider()
.override(OS.UNIX, "/path/unix/redis")
.override(OS.Windows, Architecture.x86_64, "/path/windows/redis")
.override(OS.MAC_OS_X, Architecture.x86_64, "/path/macosx/redis");

this.redisServer = new RedisServer(customProvider, redisProperties.getRedisPort());

最后,让我们创建一个使用TestRedisConfiguration类的测试吧:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestRedisConfiguration.class)
public class UserRepositoryIntegrationTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void shouldSaveUser_toRedis() {
        UUID id = UUID.randomUUID();
        User user = new User(id, "name");

        User saved = userRepository.save(user);

        assertNotNull(saved);
    }
}

这样用户保存就到了我们的嵌入式Redis服务器。

此外,我们必须手动将TestRedisConfiguration添加到SpringBootTest。正如我们之前所说,服务器在测试之前启动并在测试之后停止。

5、结论

嵌入式Redis服务器是在测试环境中替换实际服务器的完美工具。我们已经看到了如何配置它以及如何在我们的测试中使用它。

到此这篇关于嵌入式Redis服务器在Spring Boot测试中的使用的文章就介绍到这了,更多相关Redis Spring Boot使用内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Spring boot+redis实现消息发布与订阅的代码

    一.创建spring boot项目 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId>

  • SpringBoot中使用Redis的完整实例

    一.在SpringBoot中使用Redis的一套军体拳 1.导包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.2.0.RELEASE</version> </dependency> 2.导入工具类 packag

  • 基于SpringBoot2.0默认使用Redis连接池的配置操作

    SpringBoot2.0默认采用Lettuce客户端来连接Redis服务端的 默认是不使用连接池的,只有配置 redis.lettuce.pool下的属性的时候才可以使用到redis连接池 redis: cluster: nodes: ${redis.host.cluster} password: ${redis.password} lettuce: shutdown-timeout: 100 # 关闭超时时间 pool: max-active: 8 # 连接池最大连接数(使用负值表示没有限制

  • springboot2整合redis使用lettuce连接池的方法(解决lettuce连接池无效问题)

    lettuce客户端 Lettuce 和 Jedis 的都是连接Redis Server的客户端程序.Jedis在实现上是直连redis server,多线程环境下非线程安全(即多个线程对一个连接实例操作,是线程不安全的),除非使用连接池,为每个Jedis实例增加物理连接.Lettuce基于Netty的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问(即多个线程公用一个连接实例,线程安全),同时它是可伸缩的设计,一个连接

  • springboot+redis过期事件监听实现过程解析

    1 修改 redis.conf配置文件: K Keyspace events, published with keyspace@ prefix事件 E Keyevent events, published with keyevent@ prefix g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, - $ String commands l List commands s Set commands h Hash co

  • SpringBoot结合Redis哨兵模式的实现示例

    Redis哨兵模式 Redis Sentinel介绍 Redis Sentinel是Redis高可用的实现方案.Sentinel是一个管理多个Redis实例的工具,它可以实现对Redis的监控.通知.自动故障转移. Redis Sentinel主要功能 Redis 的 Sentinel 系统用于管理多个 Redis 服务器(instance), 该系统执行以下三个任务: 监控(Monitoring):Sentinel 会不断地检查你的主服务器和从服务器是否运作正常. 提醒(Notificatio

  • 嵌入式Redis服务器在Spring Boot测试中的使用教程

    1.概述 Spring Data Redis提供了一种与Redis实例集成的简单方法. 但是,在某些情况下,使用嵌入式服务器比使用真实服务器创建开发和测试环境更方便. 因此,我们将学习如何设置和使用嵌入式Redis服务器. 2.依赖 让我们首先添加必要的依赖项: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis

  • 一文搞懂阿里云服务器部署Redis并整合Spring Boot

    目录 一.什么是Redis 二.Redis的优缺点 三.阿里云服务器部署安装Redis ️在Linux服务器新建文件夹存放Redis 测试连接 四.关闭防火墙,配置Redis访问端口 配置Redis 关闭防火墙 阿里云控制台添加6379接口访问 五.Spring Boot 整合 Redis ️项目结构 核心源码 ️测试结果 总结 一.什么是Redis redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链

  • spring boot测试打包部署的方法

    有很多网友会时不时的问我,spring boot项目如何测试,如何部署,在生产中有什么好的部署方案吗?这篇文章就来介绍一下spring boot 如何开发.调试.打包到最后的投产上线. 开发阶段 单元测试 在开发阶段的时候最重要的是单元测试了,springboot对单元测试的支持已经很完善了. 1.在pom包中添加spring-boot-starter-test包引用 <dependency> <groupId>org.springframework.boot</groupI

  • 如何设置Spring Boot测试时的日志级别

    1.概览 该教程中,我将向你展示:如何在测试时设置spring boot 日志级别.虽然我们可以在测试通过时忽略日志,但是如果需要诊断失败的测试,选择正确的日志级别是非常重要的. 2.日志级别的重要性 正确设置日志级别可以节省我们许多时间. 举例来说,如果测试在CI服务器上失败,但在开发服务器上时却通过了.我们将无法诊断失败的测试,除非有足够的日志输出. 为了获取正确数量的详细信息,我们可以微调应用程序的日志级别,如果发现某个java包对我们的测试更加重要,可以给它一个更低的日志级别,比如DEB

  • Spring Boot 项目中使用Swagger2的示例

    本文介绍了Spring Boot 项目中使用Swagger2的示例,分享给大家,具体如下: 添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency&g

  • 在 Spring Boot 项目中实现文件下载功能

    (一)需求 在您的 springboot 项目中,可能会存在让用户下载文档的需求,比如让用户下载 readme 文档来更好地了解该项目的概况或使用方法. 所以,您需要为用户提供可以下载文件的 API ,将用户希望获取的文件作为下载资源返回给前端. (二)代码 maven 依赖 请您创建好一个 springboot 项目,一定要引入 web 依赖: <dependency> <groupId>org.springframework.boot</groupId> <a

  • Spring Boot项目中实现文件上传功能的示例

    在实际项目中,文件上传是很多项目必不可少的一个功能.那么在 Spring Boot 项目中又是如何来实现文件上传功能的呢?一般来说,上传的文件可以保存到项目根目录下的某一文件夹中,但这样做显然是不太合适的.因此我们选择将文件上传到专门的文件服务器中.很多云计算厂商都提供文件存储服务.这里我选择的是阿里云的对象存储(OSS). 一.配置OSS 1. 导入SDK 首先,你需要注册阿里云的账号并开通对象存储服务.在准备工作完成之后,需要导入 JAVA 版本的 SDK,这里使用 maven 进行导入 <

  • Spring Boot项目中集成微信支付v3

    1. 前言 最近忙的一批,难得今天有喘气的机会就赶紧把最近在开发中的一些成果分享出来.前几日分享了自己写的一个微信支付V3的开发包payment-spring-boot-starter,就忙里偷闲完善了一波.期间给微信支付提交了6个BUG,跟微信支付的产品沟通了好几天. 项目地址: https://github.com/NotFound403/payment-spring-boot 别忘记给个Star啊. 那么都完善了哪些内容呢?胖哥来一一介绍. 2. Maven 中央仓库 是的,不用再自行编译

  • Spring boot测试找不到SpringRunner.class的问题

    目录 Spring boot测试找不到SpringRunner.class 原因 解决方式 @RunWith(SpringRunner.class)测试SpringRunner.class找不到报红 SpringRunner报红无法添加类 问题解决 Spring boot测试找不到SpringRunner.class 原因 Maven依赖有一个<scope>,因为JUnit是直接添加到路径中,并不是通过Maven依赖加入,如果加入了<scope>会导致匹配不上         &l

  • Spring Boot/VUE中路由传递参数的实现代码

    在路由时传递参数,一般有两种形式,一种是拼接在url地址中,另一种是查询参数.如:http://localhost:8080/router/tang/101?type=spor&num=12.下面根据代码看一下,VUE 和 Spring Boot 中各自是如何处理传递和接受参数的. Spring Boot package com.tang.demo1.controller; import org.springframework.web.bind.annotation.*; @RestContro

随机推荐