Set jvmRoute in spring boot 2.0.0

拜拜、爱过 提交于 2019-12-12 09:52:21

问题


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.


回答1:


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



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!