javaspring-bootcookiesembedded-tomcat-8sticky-session

Set jvmRoute in spring boot 2.0.0


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.


Solution

  • 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);
        });
    }