2015-09-11 180 views
14

我在我的机器上使用本地Redis服务器的帮助下运行Spring启动集成测试用例,但是我想要一个不依赖于任何服务器的嵌入式Redis服务器,并且可以在任何环境内存数据库中的h2 ..?嵌入式Redis用于弹簧启动

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

} 
+0

你检查了https://github.com/kstyrc/embedded-redis –

+1

是的,我查了,但我有点困惑我的意思是我只想知道我必须创建@Bean RedisServer getserver(){}以注入它? –

回答

27

您可以使用嵌入的Redis像https://github.com/kstyrc/embedded-redis

  1. 的依赖添加到你的pom.xml
  2. 调整你的集成测试的属性,使其指向您的嵌入式Redis的,例如:

    spring: 
        redis: 
        host: localhost 
        port: 6379 
    
  3. Instanciate嵌入式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(); 
        } 
    } 
    
+0

有什么方法可以为嵌入式服务器设置密码? – Renjith

+0

可能,请查看github项目的文档,它似乎是非常可配置的 –

+4

该项目似乎不再积极维护。最后一个版本接近两年前。 –

5

您可以使用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. 使用在test configuration

    嵌入式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(); 
        } 
    } 
    
-1

你可以看到这个仓库:https://github.com/caryyu/spring-embedded-redis-server,与春春引导

行家依赖春天开机注解的使用application.yml 的

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

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

完全集成
global: 
    redis: 
     port: 6379 
     embedded: true 

+0

版本库文档为中文,如果您发现英文版,请发布链接。 –

+0

尽管这个链接可能回答这个问题,但最好在这里包含答案的基本部分,并提供供参考的链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/19027836) – ishmaelMakitla