【发布时间】:2019-03-20 14:55:47
【问题描述】:
尝试使用 Hazelcast 配置 Spring Session。使用this doc 可以开箱即用 - 但它使用默认的 hazelcast 节点。在我的情况下,我在同一个 JVM 上运行多个节点(它们位于不同的集群中),我需要使用特定的 hazelcast 实例来存储我的会话。我没有找到太多信息,如何配置它(传递 hazelcast 实例名称\或实例本身)。
将不胜感激。
【问题讨论】:
尝试使用 Hazelcast 配置 Spring Session。使用this doc 可以开箱即用 - 但它使用默认的 hazelcast 节点。在我的情况下,我在同一个 JVM 上运行多个节点(它们位于不同的集群中),我需要使用特定的 hazelcast 实例来存储我的会话。我没有找到太多信息,如何配置它(传递 hazelcast 实例名称\或实例本身)。
将不胜感激。
【问题讨论】:
接下来的代码让我配置 Spring Session 以使用特定节点,而不是默认节点。我唯一的问题是如何配置会话时间。 hazelcastSessionRepository.setDefaultMaxInactiveInterval(3600) 只设置最大不活动时间,而不是生存时间。
@Configuration
@EnableSpringHttpSession
public class HazelcastSessionConfig {
@Bean//default
public HazelcastInstance hazelcastInstance() {
Config config = new Config();
config.setInstanceName("cache-node");
config.getGroupConfig().setName("cluster-1");
return Hazelcast.newHazelcastInstance(config);
}
@Bean//Node I need to use
public HazelcastInstance hazelcastSessionInstance() {
Config config = new Config();
config.setInstanceName("session-node");
config.getGroupConfig().setName("cluster-2");
MapAttributeConfig attributeConfig = new MapAttributeConfig()
.setName(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractor(PrincipalNameExtractor.class.getName());
final MapConfig mapConfig = config.getMapConfig(HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME);
mapConfig
.addMapAttributeConfig(attributeConfig)
.addMapIndexConfig(new MapIndexConfig(
HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false));
return Hazelcast.newHazelcastInstance(config);
}
@Bean//Pass node here
public HazelcastSessionRepository sessionRepository(HazelcastInstance hazelcastSessionInstance) {
final HazelcastSessionRepository hazelcastSessionRepository = new HazelcastSessionRepository(hazelcastSessionInstance);
hazelcastSessionRepository.setDefaultMaxInactiveInterval(3600);
return hazelcastSessionRepository;
}
}
【讨论】:
接下来的代码让我配置 Spring Session 以使用特定节点,而不是默认节点。我唯一的问题是如何配置会话时间。
您是否尝试为session-node 实例设置地图配置的 TTL 秒数?如果您确保会话将存储在cluster-2 中,那么为实例设置 TTL 可以解决您的问题:
@Bean
public HazelcastInstance hazelcastSessionInstance() {
Config config = new Config();
config.setInstanceName("session-node");
config.getGroupConfig().setName("cluster-2");
MapAttributeConfig attributeConfig = new MapAttributeConfig()
.setName(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractor(PrincipalNameExtractor.class.getName());
final MapConfig mapConfig = config.getMapConfig(HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME);
mapConfig
.setTimeToLiveSeconds(300)
.addMapAttributeConfig(attributeConfig)
.addMapIndexConfig(new MapIndexConfig(
HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false));
return Hazelcast.newHazelcastInstance(config);
}
【讨论】:
会话存储跨可用节点分片。您不能选择哪个节点托管任何特定会话。此外,如果 Hazelcast 需要重新平衡分片,会话可能会从一个节点移动到另一个节点。
instance-name 参数仅指示是尝试查找与集群的现有连接还是启动新连接。
也许问题是为什么需要控制哪个节点托管哪个会话?
【讨论】: