在spring boot 2.0.0中设置jvmRoute [英] Set jvmRoute in spring boot 2.0.0

查看:434
本文介绍了在spring boot 2.0.0中设置jvmRoute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For sticky session i need to set the jvmRoute of the embedded tomcat.

实际上只有

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

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

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.

使用@PostConstruct描述这里,它不起作用(至少不在spring boot 2.0.0.RELEASE中)

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...

非常感谢任何建议。

推荐答案

您可以使用上下文自定义程序更优雅地自定义Tomcat的上下文。它是一个功能接口,因此您可以使用lambda:

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

这篇关于在spring boot 2.0.0中设置jvmRoute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆