Gurinder S Panesar Gurinder S Panesar - 4 months ago 314
Java Question

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 h2 in memory database..?

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

}

Answer

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