Spring Boot 3.x中如何设置Jetty的workerName实现粘性会话?
Spring Boot嵌入式Jetty设置workerName实现粘性会话
Spring Boot的自动配置没直接给workerName提供配置属性,得靠自定义配置类来实现,下面两种方法都能搞定:
方法一:自定义Jetty服务器工厂配置
创建配置类,通过JettyWebServerFactoryCustomizer来修改SessionIdManager的workerName:
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.eclipse.jetty.server.session.SessionIdManager; import org.eclipse.jetty.server.session.SessionManager; @Configuration public class JettySessionConfig { @Bean public WebServerFactoryCustomizer<JettyServletWebServerFactory> jettySessionCustomizer() { return factory -> { factory.addServerCustomizers(server -> { SessionManager sessionManager = server.getSessionManager(); if (sessionManager != null) { SessionIdManager idManager = sessionManager.getSessionIdManager(); if (idManager != null) { idManager.setWorkerName("foo"); } } }); }; } }
方法二:直接注册自定义SessionIdManager Bean
直接创建HashSessionIdManager实例并设置workerName,Spring Boot会自动用这个Bean替换默认的:
import org.eclipse.jetty.server.session.HashSessionIdManager; import org.eclipse.jetty.server.session.SessionIdManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JettySessionIdManagerConfig { @Bean public SessionIdManager sessionIdManager() { HashSessionIdManager idManager = new HashSessionIdManager(); idManager.setWorkerName("foo"); return idManager; } }
验证生效
启动应用后,访问任意接口,查看响应头里的JSESSIONID Cookie,会看到后缀变成.foo,说明配置成功,粘性会话的节点标识已经加上了。
内容的提问来源于stack exchange,提问作者Fergus Rataporn
相关产品推荐
相关产品推荐

