[英]Set jvmRoute in spring boot 2.0.0
对于粘性会话,我需要设置嵌入式tomcat的jvmRoute。
实际上只有一个
System.setProperty("jvmRoute", "node1");
是必需的,但我想设置一个via application.properties可配置属性。 我不知道如何以及何时使用@Value注释属性进行设置。
随着@PostConstruct所描述的在这里 ,这是行不通的(至少在春季启动2.0.0.RELEASE)
我到目前为止找到的唯一方法是
@Component
public class TomcatInitializer implements ApplicationListener<ServletWebServerInitializedEvent> {
@Value("${tomcat.jvmroute}")
private String jvmRoute;
@Override
public void onApplicationEvent(final ServletWebServerInitializedEvent event) {
final WebServer ws = event.getApplicationContext().getWebServer();
if (ws instanceof TomcatWebServer) {
final TomcatWebServer tws = (TomcatWebServer) ws;
final Context context = (Context) tws.getTomcat().getHost().findChildren()[0];
context.getManager().getSessionIdGenerator().setJvmRoute(jvmRoute);
}
}
}
它有效,但看起来不那么优雅......
任何建议都非常感谢。
您可以使用上下文自定义程序更优雅地自定义Tomcat的Context
。 它是一个功能界面,所以你可以使用lambda:
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatCustomizer() {
return (tomcat) -> tomcat.addContextCustomizers((context) -> {
Manager manager = context.getManager();
if (manager == null) {
manager = new StandardManager();
context.setManager(manager);
}
manager.getSessionIdGenerator().setJvmRoute(jvmRoute);
});
}
我正在使用Spring Boot 2.0.4。 上面的答案一直对我不起作用。 我不得不这样更新它:
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> servletContainer() {
return (tomcat) -> {
tomcat.addContextCustomizers((context) -> {
Manager manager = context.getManager();
if (manager == null) {
manager = new StandardManager();
context.setManager(manager);
}
((ManagerBase) context.getManager()).getEngine().setJvmRoute("tomcatJvmRoute");
});
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.