Spring Session Hazelcast并发控制Tomcat上的多个JVM



产品版本:弹簧引导启动器父2.6.0com.hazelcast.hazelcast 5.0春季会议榛子铸造2.6.0com.hazelcast.hazelcast-all-4.2.2春季会议核心2.6.0弹簧启动装置安全2.6.0

尝试使用Embedded Hazelcast集群来支持Tomcat上运行的多个JVM实例之间的会话复制和会话并发控制。

我正在尝试了解如何使用SpringSessionBackedSession注册表类,该类支持跨多个JVM的并发性,而标准SessionRegistryImpl则不支持。Hazelcast实例创建:

@Bean(name = "hazelcastinstance")
@SpringSessionHazelcastInstance
public HazelcastInstance hazelcastInstance() {
Config hazelcastConfiguration = new Config();
hazelcastConfiguration.setClusterName("sp-cluster");
hazelcastConfiguration.setInstanceName("hazelsessionstore");
NetworkConfig hazelcastNetworkConfig = hazelcastConfiguration.getNetworkConfig();
hazelcastNetworkConfig.setPort(hazelcastPort);
JoinConfig hazelcastJoin = hazelcastNetworkConfig.getJoin();
hazelcastJoin.getAutoDetectionConfig().setEnabled(false);
hazelcastJoin.getTcpIpConfig().setEnabled(true);
hazelcastJoin.getMulticastConfig().setEnabled(false);
// Add cluster members to allowable TCP IP instance from properties array
for (String hazelMember : hazelcastMembers) {
hazelcastJoin.getTcpIpConfig().addMember(hazelMember);
}
// Add this attribute to be able to query sessions by their
// PRINCIPAL_NAME_ATTRIBUTE's
AttributeConfig attributeConfig = new AttributeConfig()
.setName(Hazelcast4IndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(Hazelcast4PrincipalNameExtractor.class.getName());
// Configure the sessions map
hazelcastConfiguration.getMapConfig(HAZEL_MAP).addAttributeConfig(attributeConfig)
.addIndexConfig(
new IndexConfig(IndexType.HASH, Hazelcast4IndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE))
.setMaxIdleSeconds(serverSessionInactiveTimeout);
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setImplementation(new HazelcastSessionSerializer()).setTypeClass(MapSession.class);
hazelcastConfiguration.getSerializationConfig().addSerializerConfig(serializerConfig);
System.out.println("Multicast configuration is enabled: "
+ hazelcastConfiguration.getNetworkConfig().getJoin().getMulticastConfig().isEnabled());
return Hazelcast.newHazelcastInstance(hazelcastConfiguration);
}

Hazelcast会话报告自定义

@Bean(name = "hazelcastrepo")
public SessionRepositoryCustomizer<Hazelcast4IndexedSessionRepository> customize() {
return (sessionRepository) -> {
System.out.println("*******Session Repo Customizer Invoked");
sessionRepository.setApplicationEventPublisher(this.applicationEventPublisher);
sessionRepository.setFlushMode(FlushMode.IMMEDIATE);
sessionRepository.setFlushMode(FlushMode.ON_SAVE);
sessionRepository.setSaveMode(SaveMode.ALWAYS);
sessionRepository.setSessionMapName(HAZEL_MAP);
sessionRepository.setDefaultMaxInactiveInterval(serverSessionInactiveTimeout);
setSessionRepository(sessionRepository);
};
}

Hazelcast会话复制设置

@DependsOn("hazelcastinstance")
@Bean
public com.hazelcast.web.spring.SpringAwareWebFilter webFilter() {
Properties properties = new Properties();

properties.put("instance-name", "hazelsessionstore");
properties.put("use-client", false);
properties.put("sticky-session", "false");
return new com.hazelcast.web.spring.SpringAwareWebFilter(properties);
}

Security Config适用部分,我尝试手动将SessionRegistry设置为SpringSessionBackedSessionRegistry的实例。***这就是我出现错误的地方,tomcat无法启动,出现异常:


@Autowired private HazelcastHttpSessionConfig sessionConfig;
@Bean
SpringSessionBackedSessionRegistry sessionRegistry() {
return new SpringSessionBackedSessionRegistry( sessionConfig.getSessionRepository());
}
@Bean 
public HttpSessionEventPublisher httpSessionEventPublisher() {

return new HttpSessionEventPublisher(); }

@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
try {

httpSecurity
.csrf().disable()
.cors().disable();


httpSecurity.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)

.maximumSessions(sessionConcurrentLimit)
.sessionRegistry(sessionRegistry())
.maxSessionsPreventsLogin(sessionPreventLogin)
.expiredUrl("/user?multipleloginsdetected")
.and()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("/user?expiredsession");

***例外

2021-11-22 13:46:23.080  WARN 84700 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionRepositoryFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.class]: Unsatisfied dependency expressed through method 'sessionRepositoryFilterRegistration' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.session.hazelcast.config.annotation.web.http.HazelcastHttpSessionConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hazelcastHttpSessionConfig' defined in file [C:UsersmyuserDocumentseclipse-workspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebappsmyappWEB-INFclassescommyappHazelcastHttpSessionConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.myapp.HazelcastHttpSessionConfig$$EnhancerBySpringCGLIB$$7ff667f1]: Constructor threw exception; nested exception is java.lang.IllegalStateException: BeanFactory has not been injected into @Configuration class
2021-11-22 13:46:23.112  INFO 84700 --- [           main] ConditionEvaluationReportLoggingListener : 
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-11-22 13:46:23.210 ERROR 84700 --- [           main] o.s.boot.SpringApplication               : Application run failed
org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionRepositoryFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.class]: Unsatisfied dependency expressed through method 'sessionRepositoryFilterRegistration' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.session.hazelcast.config.annotation.web.http.HazelcastHttpSessionConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hazelcastHttpSessionConfig' defined in file [C:UsersmyuserDocumentseclipse-workspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebappsmyappWEB-INFclassescommyappHazelcastHttpSessionConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com..myapp.HazelcastHttpSessionConfig$$EnhancerBySpringCGLIB$$7ff667f1]: Constructor threw exception; nested exception is java.lang.IllegalStateException: BeanFactory has not been injected into @Configuration class
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:163) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:577) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:175) [spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:155) [spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:97) [spring-boot-2.6.0.jar:2.6.0]
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174) [spring-web-5.3.13.jar:5.3.13]
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5219) [catalina.jar:9.0.55]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [catalina.jar:9.0.55]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) [catalina.jar:9.0.55]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) [catalina.jar:9.0.55]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_291]
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) [tomcat-util.jar:9.0.55]
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) [na:1.8.0_291]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) [catalina.jar:9.0.55]
at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:835) [catalina.jar:9.0.55]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [catalina.jar:9.0.55]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1396) [catalina.jar:9.0.55]
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1386) [catalina.jar:9.0.55]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_291]
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) [tomcat-util.jar:9.0.55]
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) [na:1.8.0_291]
at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:919) [catalina.jar:9.0.55]
at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:263) [catalina.jar:9.0.55]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [catalina.jar:9.0.55]
at org.apache.catalina.core.StandardService.startInternal(StandardService.java:432) [catalina.jar:9.0.55]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [catalina.jar:9.0.55]
at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:927) [catalina.jar:9.0.55]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) [catalina.jar:9.0.55]
at org.apache.catalina.startup.Catalina.start(Catalina.java:772) [catalina.jar:9.0.55]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_291]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_291]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_291]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_291]
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:345) [bootstrap.jar:9.0.55]
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:476) [bootstrap.jar:9.0.55]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionRepositoryFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/session/SessionRepositoryFilterConfiguration.class]: Unsatisfied dependency expressed through method 'sessionRepositoryFilterRegistration' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.session.hazelcast.config.annotation.web.http.HazelcastHttpSessionConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hazelcastHttpSessionConfig' defined in file [C:UsersmyuserDocumentseclipse-workspace.metadata.pluginsorg.eclipse.wst.server.coretmp0wtpwebappsmyappWEB-INFclassescom\myappHazelcastHttpSessionConfig.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com..myapp.HazelcastHttpSessionConfig$$EnhancerBySpringCGLIB$$7ff667f1]: Constructor threw exception; nested exception is java.lang.IllegalStateException: BeanFactory has not been injected into @Configuration class
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:541) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213) ~[spring-beans-5.3.13.jar:5.3.13]
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:212) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:203) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addServletContextInitializerBeans(ServletContextInitializerBeans.java:97) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:86) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getServletContextInitializerBeans(ServletWebServerApplicationContext.java:260) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.selfInitialize(ServletWebServerApplicationContext.java:234) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:191) ~[spring-boot-2.6.0.jar:2.6.0]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:160) ~[spring-boot-2.6.0.jar:2.6.0]
... 38 common frames omitted

感谢您的帮助。spring-session-hazalcast中的@Annotation方法之一是否应该自动将默认的SessionRegistry替换为SpringSessionBackedSessionRegistry实例?如果是这样的话,在我的案例中似乎不会发生这种情况,默认的SessionRegistry就是它所使用的。谢谢

好的,所以我能够通过在与我的安全配置相同的类中设置Hazelcast bean来实现这一点。不一定喜欢它不适用于其他类中的HZ设置,但可能是bean创建问题或SessionRepository中的自动布线导致了问题。对于那些在让多个JVM进行嵌入式Hazelcast会话复制和会话并发控制方面遇到困难的人来说,这里是我在两个Tomcat9实例上运行的工作解决方案:

package com.myapp;
import java.util.Properties;
import java.util.Set;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.session.FlushMode;
import org.springframework.session.MapSession;
import org.springframework.session.SaveMode;
import org.springframework.session.Session;
import org.springframework.session.config.SessionRepositoryCustomizer;
import org.springframework.session.hazelcast.Hazelcast4IndexedSessionRepository;
import org.springframework.session.hazelcast.Hazelcast4PrincipalNameExtractor;
import org.springframework.session.hazelcast.HazelcastSessionSerializer;
import org.springframework.session.hazelcast.config.annotation.SpringSessionHazelcastInstance;
import org.springframework.session.hazelcast.config.annotation.web.http.EnableHazelcastHttpSession;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;
import com.hazelcast.config.AttributeConfig;
import com.hazelcast.config.Config;
import com.hazelcast.config.IndexConfig;
import com.hazelcast.config.IndexType;
import com.hazelcast.config.JoinConfig;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.config.SerializerConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.myapp.service.authentication.LoginFailureHandlerService;
import com.myapp.service.authentication.LoginSuccessHandlerService;
import com.myapp.service.eventlisteners.CustomAccessDeniedHandler;

@Configuration
@EnableWebSecurity
@EnableHazelcastHttpSession
public class SecurityConfig<S extends Session> extends WebSecurityConfigurerAdapter {

@Value("${ldap.base.dn}")
private String ldapBaseDn;
@Value("${ldap.admin.dn}")
private String ldapSecurityPrincipal;
@Value("${ldap.admin.password}")
private String ldapPrincipalPassword;
@Value("${ldap.url}")
private String ldapUrl;
@Value("${username.search.password}")
private String ldapUserPassword;
@Value("${username.search.pattern}")
private String ldapUserSearchPattern;
@Value("${myapp.cookiename}")
private String myappCookieName;

@Value("${session.concurrentlimit}")
private Integer sessionConcurrentLimit;

@Value("${session.preventlogin}")
private Boolean sessionPreventLogin;
private final static Logger logger = LoggerFactory.getLogger("" + SecurityConfig.class);


@Bean 
public HttpSessionEventPublisher httpSessionEventPublisher() {

return new HttpSessionEventPublisher(); 

}


@Bean
public LoginSuccessHandlerService ldaploginsuccesshandler() {
return new LoginSuccessHandlerService();
}
@Bean
public AuthenticationFailureHandler ldaploginfailurehandler() {
return new LoginFailureHandlerService();
}

private String HAZEL_MAP = "HAZEL_MAP";
@Value("${server.servlet.session.timeout}")
private Integer serverSessionInactiveTimeout;
@Value("${hazelcast.members}")
private String[] hazelcastMembers;
@Value("${hazelcast.port}")
private Integer hazelcastPort;
@Autowired
private ApplicationEventPublisher applicationEventPublisher;

private Hazelcast4IndexedSessionRepository sessionRepository;

@Bean(name = "hazelcastrepo")
public SessionRepositoryCustomizer<Hazelcast4IndexedSessionRepository> customize() {
return (sessionRepository) -> {
sessionRepository.setApplicationEventPublisher(this.applicationEventPublisher);
sessionRepository.setFlushMode(FlushMode.IMMEDIATE);
sessionRepository.setFlushMode(FlushMode.ON_SAVE);
sessionRepository.setSaveMode(SaveMode.ALWAYS);
sessionRepository.setSessionMapName(HAZEL_MAP);
sessionRepository.setDefaultMaxInactiveInterval(serverSessionInactiveTimeout);
setSessionRepository(sessionRepository);

};
}

@Bean(name = "hazelcastinstance")
@SpringSessionHazelcastInstance
public HazelcastInstance hazelcastInstance() {

Config hazelcastConfiguration = new Config();
hazelcastConfiguration.setClusterName("myapp-cluster");
hazelcastConfiguration.setInstanceName("hazelsessionstore");
NetworkConfig hazelcastNetworkConfig = hazelcastConfiguration.getNetworkConfig();
hazelcastNetworkConfig.setPort(hazelcastPort);
JoinConfig hazelcastJoin = hazelcastNetworkConfig.getJoin();
hazelcastJoin.getAutoDetectionConfig().setEnabled(false);
hazelcastJoin.getTcpIpConfig().setEnabled(true);
hazelcastJoin.getMulticastConfig().setEnabled(false);
// Add cluster members to allowable TCP IP instance from properties array
for (String hazelMember : hazelcastMembers) {
hazelcastJoin.getTcpIpConfig().addMember(hazelMember);
}
// Add this attribute to be able to query sessions by their
// PRINCIPAL_NAME_ATTRIBUTE's
AttributeConfig attributeConfig = new AttributeConfig()
.setName(Hazelcast4IndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractorClassName(Hazelcast4PrincipalNameExtractor.class.getName());
// Configure the sessions map
hazelcastConfiguration.getMapConfig(HAZEL_MAP).addAttributeConfig(attributeConfig)
.addIndexConfig(
new IndexConfig(IndexType.HASH, Hazelcast4IndexedSessionRepository.PRINCIPAL_NAME_ATTRIBUTE))
.setMaxIdleSeconds(serverSessionInactiveTimeout);
// Use custom serializer to de/serialize sessions faster. This is optional.
// Note that, all members in a cluster and connected clients need to use the
// same serializer for sessions. For instance, clients cannot use this
// serializer // where members are not configured to do so.
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setImplementation(new HazelcastSessionSerializer()).setTypeClass(MapSession.class);
hazelcastConfiguration.getSerializationConfig().addSerializerConfig(serializerConfig);

return Hazelcast.newHazelcastInstance(hazelcastConfiguration);
}

@DependsOn("hazelcastinstance")
@Bean
public com.hazelcast.web.spring.SpringAwareWebFilter webFilter() {
Properties properties = new Properties();
Set<HazelcastInstance> hzSet = com.hazelcast.core.Hazelcast.getAllHazelcastInstances();
hzSet.forEach(set -> {
System.out.println("Hazel Instance Name: " + set.getName());
});
properties.put("instance-name", "hazelsessionstore");
properties.put("use-client", false);
properties.put("sticky-session", "false");
return new com.hazelcast.web.spring.SpringAwareWebFilter(properties);
}

@DependsOn("hazelcastinstance")
@Bean
SpringSessionBackedSessionRegistry sessionRegistry() {
return new SpringSessionBackedSessionRegistry(getSessionRepository() );
}

@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
try {

httpSecurity
.csrf().disable()
.cors().disable();


httpSecurity.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)

.maximumSessions(sessionConcurrentLimit)
.sessionRegistry(sessionRegistry())
.maxSessionsPreventsLogin(sessionPreventLogin)
.expiredUrl("/user?multipleloginsdetected")
.and()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("/user?expiredsession");



httpSecurity
*** NON RELEVANT SECURITY REDACTED***


}


public Hazelcast4IndexedSessionRepository getSessionRepository() {
return sessionRepository;
}

public void setSessionRepository(Hazelcast4IndexedSessionRepository sessionRepository) {
this.sessionRepository = sessionRepository;
}
}

最新更新