运行spring boot测试时遇到hazelcast.core.DuplicateInstanceNameException

时间:2018-03-16 14:40:57

标签: spring-boot integration-testing hazelcast

如何使用Hazelcast执行spring boot应用程序的集成测试,因为运行时所有测试都获得了hazelcast.core.DuplicateInstanceNameException?

我使用Spring Boot 2.0.0.RC1 和Hazelcast 3.9.2

使用java配置进行hazelcast:

@Bean
public Config getHazelCastServerConfig() {
    final Config config = new Config();
    config.setInstanceName(hzInstance);
    config.getGroupConfig().setName(hzGroupName).setPassword(hzGroupPassword);

    final ManagementCenterConfig managementCenterConfig = config.getManagementCenterConfig();
    managementCenterConfig.setEnabled(true);
    managementCenterConfig.setUrl(mancenter);

    final MapConfig mapConfig = new MapConfig();
    mapConfig.setName(mapName);
    mapConfig.setEvictionPolicy(EvictionPolicy.NONE);
    mapConfig.setTimeToLiveSeconds(0);
    mapConfig.setMaxIdleSeconds(0);

    config.getScheduledExecutorConfig(scheduler)
            .setPoolSize(16)
            .setCapacity(100)
            .setDurability(1);

    final NetworkConfig networkConfig = config.getNetworkConfig();
    networkConfig.setPort(5701);
    networkConfig.setPortAutoIncrement(true).setPortCount(30);

    final JoinConfig joinConfig = networkConfig.getJoin();
    joinConfig.getMulticastConfig().setEnabled(false);
    joinConfig.getAwsConfig().setEnabled(false);

    final TcpIpConfig tcpIpConfig = joinConfig.getTcpIpConfig();
    tcpIpConfig.addMember(memberOne)
            .addMember(memberTwo);
    tcpIpConfig.setEnabled(true);

    return config;
}

@Bean
public HazelcastInstance getHazelCastServerInstance() {
    final HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(getHazelCastServerConfig());
    hazelcastInstance.getClientService().addClientListener(new ClientListener() {
        @Override
        public void clientConnected(Client client) {
            System.out.println(String.format("Connected %s %s %s", client.getClientType(), client.getUuid(), client.getSocketAddress()));
            log.info(String.format("Connected %s %s %s", client.getClientType(), client.getUuid(), client.getSocketAddress()));
        }

        @Override
        public void clientDisconnected(Client client) {
            System.out.println(String.format("Disconnected %s %s %s", client.getClientType(), client.getUuid(), client.getSocketAddress()));
            log.info(String.format("Disconnected %s %s %s", client.getClientType(), client.getUuid(), client.getSocketAddress()));
        }
    });

    return hazelcastInstance;
}

我有简单的测试:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = UpaSdcApplication.class)
@ActiveProfiles("test")
 public class CheckEndpoints {

@Autowired
private ApplicationContext context;

private static final String HEALTH_ENDPOINT = "/actuator/health";

private static WebTestClient testClient;

@Before
public void init() {
    testClient = org.springframework.test.web.reactive.server.WebTestClient
            .bindToApplicationContext(context)
            .configureClient()
            .filter(basicAuthentication())
            .build();
}

@Test
public void testHealth(){
    testClient.get().uri(HEALTH_ENDPOINT).accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus()
            .isOk()
            .expectBody()
            .json("{\"status\": \"UP\"}");
}
}

如果与其他测试分开运行测试类 - 它会执行正常并通过。 如果用其他测试运行 - 获得异常:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.hazelcast.core.HazelcastInstance]: Factory method 'getHazelCastServerInstance' threw exception; nested exception is com.hazelcast.core.DuplicateInstanceNameException: HazelcastInstance with name 'counter-instance' already exists!
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
    ... 91 more
Caused by: com.hazelcast.core.DuplicateInstanceNameException: HazelcastInstance with name 'counter-instance' already exists!
    at com.hazelcast.instance.HazelcastInstanceFactory.newHazelcastInstance(HazelcastInstanceFactory.java:170)
    at com.hazelcast.instance.HazelcastInstanceFactory.newHazelcastInstance(HazelcastInstanceFactory.java:124)
    at com.hazelcast.core.Hazelcast.newHazelcastInstance(Hazelcast.java:58)
    at net.kyivstar.upa.sdc.config.HazelcastConfiguration.getHazelCastServerInstance(HazelcastConfiguration.java:84)
    at net.kyivstar.upa.sdc.config.HazelcastConfiguration$$EnhancerBySpringCGLIB$$c7da65f3.CGLIB$getHazelCastServerInstance$0(<generated>)
    at net.kyivstar.upa.sdc.config.HazelcastConfiguration$$EnhancerBySpringCGLIB$$c7da65f3$$FastClassBySpringCGLIB$$b920d5ef.invoke(<generated>)

你如何解决这个问题?你如何运行集成测试?

3 个答案:

答案 0 :(得分:2)

instanceName配置元素用于创建命名的Hazelcast成员,并且对于JVM中的每个Hazelcast实例应该是唯一的。在您的情况下,您应该为同一JVM中的每个HazelcastInstance bean创建设置不同的实例名称,或者如果您不使用实例名称调用实例,则可以完全删除instanceName配置

答案 1 :(得分:0)

运行测试时遇到了相同的问题。在我的情况下,原因是,弹簧测试框架试图启动新的上下文,同时保留旧的上下文-从而试图创建另一个具有相同名称的hazelcast实例,而一个实例已经在缓存的上下文中。

  

一旦TestContext框架加载了ApplicationContext(或   WebApplicationContext)进行测试,该上下文被缓存并重用   对于所有声明相同唯一上下文的后续测试   在同一测试套件中进行配置。

阅读here,以了解有关Spring Test Framework如何管理测试上下文的更多信息。 我目前正在解决该问题,稍后再发布。我可以看到的一种可能的解决方案是在每次使用@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)进行测试后都删除测试上下文,但这在性能方面非常昂贵。

答案 2 :(得分:0)

我遇到了同样的问题,我通过检查实例是否已经存在来解决它:

@Bean
public CacheManager cacheManager() {
    HazelcastInstance existingInstance = Hazelcast.getHazelcastInstanceByName(CACHE_INSTANCE_NAME);
    HazelcastInstance hazelcastInstance = null != existingInstance 
         ? existingInstance                                                                       
         : Hazelcast.newHazelcastInstance(hazelCastConfig());
    return new HazelcastCacheManager(hazelcastInstance);
}

您可以看到其余的代码here