如何在Spring Boot中配置Hazelcast主机端口?

时间:2017-11-10 15:57:42

标签: spring hazelcast

我在我的项目中使用了hazelcast,并且不会将hazelcast host:port信息移动到环境变量中。在此之前,我使用了下一个查看的默认配置:

<hazelcast-client xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://www.hazelcast.com/schema/client-config
                               http://www.hazelcast.com/schema/client-config/hazelcast-client-config-3.8.xsd"
                  xmlns="http://www.hazelcast.com/schema/client-config">

    <network>
        <connection-timeout>3000</connection-timeout>
        <connection-attempt-period>1000</connection-attempt-period>
        <connection-attempt-limit>259200</connection-attempt-limit>
    </network>

</hazelcast-client>

因此,我发现可以在<cluster-members>中添加<network>标记,以便为hazelcast实例提供自定义<address>。我已将hazelcast.xml文件修改为:

<network>
    <cluster-members>
        <address>${HAZELCAST_URL}</address>
    </cluster-members>
    ...

但每当我启动我的应用程序时,它会显示:

2017-11-10 17:55:45 [service,,,] WARN  c.h.c.s.i.ClusterListenerSupport hz.client_0 [dev] [3.8.5] Exception during initial connection to ${HAZELCAST_URL}:5701, exception java.lang.IllegalArgumentException: Can't resolve address: ${HAZELCAST_URL}:5701
2017-11-10 17:55:45 [service,,,] WARN  c.h.c.s.i.ClusterListenerSupport hz.client_0 [dev] [3.8.5] Exception during initial connection to ${HAZELCAST_URL}:5702, exception java.lang.IllegalArgumentException: Can't resolve address: ${HAZELCAST_URL}:5702

因此它仍然尝试连接到默认端口,并且还没有解析变量。有没有办法配置它?

1 个答案:

答案 0 :(得分:0)

您可以将java.util.Properties传递到客户端配置构建器。您所需要做的就是从Spring的环境中构建它。

@Bean
public ClientConfig clientConfig(Environment environment) throws Exception {
        Properties properties = new Properties();
        String HAZELCAST_URL = "HAZELCAST_URL";
        properties.put(HAZELCAST_URL, environment.getProperty(HAZELCAST_URL));
        XmlClientConfigBuilder xmlClientConfigBuilder = new XmlClientConfigBuilder("hazelcast-client.xml");
        xmlClientConfigBuilder.setProperties(properties);
        return xmlClientConfigBuilder.build();
}

@Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
        return HazelcastClient.newHazelcastClient(clientConfig);
}

请注意,有更优雅的方法可以做到这一点,上面只是一个解决方案,尽可能简单