Java 用于 Spring Boot 的嵌入式 Redis

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32524194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:42:28  来源:igfitidea点击:

Embedded Redis for Spring Boot

javaredisspring-boot

提问by Gurinder

I run my Integration Test cases with Spring Boot with the help of my local Redis server on my machine.

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

But I want an embedded Redis server which is not dependent on any server and can run on any environment, like the H2 in-memory database. How can I do it?

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

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

}

采纳答案by Sébastien Nussbaumer

You can use an embedded Redis like https://github.com/kstyrc/embedded-redis

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

  1. Add the dependency to your pom.xml
  2. Adjust the properties for your integration test to point to your embedded redis, for example :

    spring:
      redis:
        host: localhost
        port: 6379
    
  3. Instanciate the embedded redis server in a component that is defined in your tests only :

    @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();
        }
    }
    
  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();
        }
    }
    

回答by Markus Schulte

You can use ozimov/embedded-redisas a Maven(-test)-dependency (this is the successor of kstyrc/embedded-redis).

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

  1. Add the dependency to your pom.xml

    <dependencies>
      ...
      <dependency>
        <groupId>it.ozimov</groupId>
        <artifactId>embedded-redis</artifactId>
        <version>0.7.1</version>
        <scope>test</scope>
      </dependency>
    
  2. Adjust your application properties for your integration test

    spring.redis.host=localhost
    spring.redis.port=6379
    
  3. Use the embedded redis server in a test configuration

    @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();
      }
    }
    
  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();
      }
    }
    

回答by Caryyu

you can see this repository: https://github.com/caryyu/spring-embedded-redis-server, fully integrated with Spring and Spring Boot

你可以看到这个仓库:https: //github.com/caryyu/spring-embedded-redis-server,与 Spring 和 Spring Boot 完全集成

maven dependency

Maven 依赖

<dependency>
<groupId>com.github.caryyu</groupId>
<artifactId>spring-embedded-redis-server</artifactId>
<version>1.1</version>
</dependency>

spring boot annotation

弹簧靴注解

@Bean
public RedisServerConfiguration redisServerConfiguration() {
return new RedisServerConfiguration();
}

usage of application.yml

application.yml 的使用

spring:
    redis:
        port: 6379
        embedded: true

回答by magiccrafter

Another neat way is to use the testcontainerslibrary which can run any type of application that can in a Docker container and Redis is no exception. What I like best is that it is lightly coupled with the Spring Test ecosystem.

另一个巧妙的方法是使用testcontainers可以在 Docker 容器中运行任何类型的应用程序的库,Redis 也不例外。我最喜欢的是它与 Spring Test 生态系统的结合。

maven's dependency:

maven 的依赖:

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers</artifactId>
    <version>${testcontainers.version}</version>
</dependency>

simple integration test:

简单的集成测试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {"management.port=0"})
@ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class)
@DirtiesContext
public abstract class AbstractIntegrationTest {

    private static int REDIS_PORT = 6379;

    @ClassRule
    public static GenericContainer redis = new GenericContainer("redis:3.0.6").withExposedPorts(REDIS_PORT);

    public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(ConfigurableApplicationContext ctx) {
            // Spring Boot 1.5.x
            TestPropertySourceUtils.addInlinedPropertiesToEnvironment(ctx,
                "spring.redis.host=" + redis.getContainerIpAddress(),
                "spring.redis.port=" + redis.getMappedPort(REDIS_PORT));

            // Spring Boot 2.x.
            TestPropertyValues.of(
                "spring.redis.host:" + redis.getContainerIpAddress(),
                "spring.redis.port:" + redis.getMappedPort(REDIS_PORT))
                .applyTo(ctx);
        }
    }
}