SpringBoot中RedisCluster的相关测试配置

如果SpringBoot的项目中用到了RedisCluster,那么如何在测试中配置RedisCluster呢?

这个问题比较抽象,我们可以细分一下有可能遇到哪些测试的问题。

比如,我在RedisCluster中添加了一些东西,我们希望在每次测试之前都清空一下,那该如何实现?

首先假设我们已经有了一个3master,3salve的RedisCluster,我们需要添加配置。

1
2
3
4
5
6
7
8
//application.properties

spring.redis.cluster.nodes[0]=redis:7000
spring.redis.cluster.nodes[1]=redis:7001
spring.redis.cluster.nodes[2]=redis:7002
spring.redis.cluster.nodes[3]=redis:7003
spring.redis.cluster.nodes[4]=redis:7004
spring.redis.cluster.nodes[5]=redis:7005

其次,添加JavaConfigration,这个可能已经在项目中有了,所以在test的package下面,并不需要再添加一次。

1
2
3
4
5
6
7
8
9
10
11
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterConf {
List<String> nodes;

@Bean
public RedisConnectionFactory connectionFactory() {
return new JedisConnectionFactory(new RedisClusterConfiguration(nodes));
}
}

测试的时候会自动读取测试环境下的properties。

接下来就是在开始和结束测试之前,清空Redis。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@ExtendWith(SpringExtension.class)
@SpringBootTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MyServiceTest {

@Autowired
RedisConnectionFactory redisConnectionFactory;

@BeforeAll
@AfterAll
void resetRedis(){
redisConnectionFactory.getConnection().flushAll();
}

@Test
//...

}