You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:24:56