Подтвердить что ты не робот

Встроенный Redis для Spring Boot

Я запускаю свои тесты интеграции с Spring Boot с помощью моего локального сервера Redis на моей машине.

Но мне нужен встроенный сервер Redis, который не зависит от какого-либо сервера и может работать в любой среде, например, в базе данных H2 в памяти. Как мне это сделать?

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

}
4b9b3361

Ответ 1

Вы можете использовать встроенный Redis, например https://github.com/kstyrc/embedded-redis

  • Добавьте зависимость к вашему pom.xml
  • Отрегулируйте свойства вашего теста интеграции, чтобы указать на ваш внедренный redis, например:

    spring:
      redis:
        host: localhost
        port: 6379
    
  • Включить встроенный сервер 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) - зависимость (это наследник 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();
      }
    }
    

Ответ 3

Другой testcontainers способ - использовать библиотеку testcontainers которая может запускать приложения любого типа, которые могут находиться в контейнере Docker, и Redis не является исключением. Что мне нравится больше всего, так это то, что он слегка связан с экосистемой Spring Test.

Maven зависимость:

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

простой интеграционный тест:

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

Ответ 4

Вы можете увидеть этот репозиторий: https://github.com/caryyu/spring-embedded-redis-server, полностью интегрированный с Spring и Spring Boot

Maven зависимость

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

весенняя загрузка аннотации

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

использование application.yml

spring:
    redis:
        port: 6379
        embedded: true