For sticky session i need to set the jvmRoute of the embedded tomcat.
Actually only a
System.setProperty("jvmRoute", "node1");
is required, but i want to set a via application.properties configurable property. I don't know how and when to set this with @Value annotated property.
With @PostConstruct as described here, it does not work (at least not in spring boot 2.0.0.RELEASE)
The only way i found so far is
@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);
}
}
}
It works, but it does not look like much elegant...
Any suggestions are very appreciated.
You can customise Tomcat's Context
a little more elegantly by using a context customiser. It's a functional interface so you can use a 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);
});
}
I'm using Spring Boot 2.0.4. The above answer did not work for me all the way. I had to update it this way:
@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");
});
};
}
来源:https://stackoverflow.com/questions/49621813/set-jvmroute-in-spring-boot-2-0-0