2015-09-11 54 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