在spring boot 2.0.0中设置jvmRoute

对于粘性会话,我需要设置嵌入式tomcat的jvmRoute。

实际上只有一个

System.setProperty("jvmRoute", "node1"); 

是必需的,但我想设置一个via application.properties可配置属性。 我不知道如何以及何时使用@Value注释属性进行设置。

使用@PostConstruct,如此处所述,它不起作用(至少不在spring boot 2.0.0.RELEASE中)

我到目前为止找到的唯一方法是

  @Component public class TomcatInitializer implements ApplicationListener { @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 。 它是一个function界面,所以你可以使用lambda:

 @Bean public WebServerFactoryCustomizer 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 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"); }); }; }