Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedded Redis for Spring Boot

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

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?

@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @IntegrationTest("server.port:0") @SpringApplicationConfiguration(classes = Application.class)  @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class MasterIntegrationTest {  } 
like image 645
Gurinder Avatar asked Sep 11 '15 13:09

Gurinder


People also ask

What is Redis in spring boot?

Redis is driven by a keystore-based data structure to persist data and can be used as a database, cache, message broker, etc. We'll be able to use the common patterns of Spring Data (templates, etc.) while also having the traditional simplicity of all Spring Data projects.


2 Answers

You can use an embedded Redis like 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();     } } 
like image 126
Sébastien Nussbaumer Avatar answered Sep 18 '22 17:09

Sébastien Nussbaumer


You can use ozimov/embedded-redis as a Maven(-test)-dependency (this is the successor of 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();   } } 
like image 44
Markus Schulte Avatar answered Sep 19 '22 17:09

Markus Schulte