Set jvmRoute in spring boot 2.0.0

2019-05-16 14:57发布

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.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-16 15:45

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");

        });
    };
}
查看更多
Evening l夕情丶
3楼-- · 2019-05-16 15:49

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);
    });
}
查看更多
登录 后发表回答