嵌入式 Redis for Spring Boot

2022-09-01 04:55:53

我在计算机上的本地 Redis 服务器的帮助下,使用 Spring Boot 运行集成测试用例。

但是我想要一个嵌入式Redis服务器,它不依赖于任何服务器,可以在任何环境中运行,比如H2内存数据库。我该怎么做?

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
@SpringApplicationConfiguration(classes = Application.class) 
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class MasterIntegrationTest {

}

答案 1

您可以使用嵌入式 Redis,例如 https://github.com/kstyrc/embedded-redis

  1. 将依赖项添加到您的 pom 中.xml
  2. 调整集成测试的属性以指向嵌入式 redis,例如:

    spring:
      redis:
        host: localhost
        port: 6379
    
  3. 将嵌入式 redis 服务器实例化到仅在测试中定义的组件中:

    @Component
    public class EmbededRedis {
    
        @Value("${spring.redis.port}")
        private int redisPort;
    
        private RedisServer redisServer;
    
        @PostConstruct
        public void startRedis() throws IOException {
            redisServer = new RedisServer(redisPort);
            redisServer.start();
        }
    
        @PreDestroy
        public void stopRedis() {
            redisServer.stop();
        }
    }
    

答案 2

您可以使用 ozimov/embedded-redis 作为 Maven(-test)-dependency(这是 kstyrc/embedded-redis 的继承者)。

  1. 将依赖项添加到您的 pom 中.xml

    <dependencies>
      ...
      <dependency>
        <groupId>it.ozimov</groupId>
        <artifactId>embedded-redis</artifactId>
        <version>0.7.1</version>
        <scope>test</scope>
      </dependency>
    
  2. 调整应用程序属性以进行集成测试

    spring.redis.host=localhost
    spring.redis.port=6379
    
  3. 测试配置中使用嵌入式 redis 服务器

    @TestConfiguration
    public static class EmbededRedisTestConfiguration {
    
      private final redis.embedded.RedisServer redisServer;
    
      public EmbededRedisTestConfiguration(@Value("${spring.redis.port}") final int redisPort) throws IOException {
        this.redisServer = new redis.embedded.RedisServer(redisPort);
      }
    
      @PostConstruct
      public void startRedis() {
        this.redisServer.start();
      }
    
      @PreDestroy
      public void stopRedis() {
        this.redisServer.stop();
      }
    }
    

推荐