【问题标题】:How to getDistributable() in Java Spring Boot?如何在 Java Spring Boot 中获取分布式()?
【发布时间】:2017-09-16 06:24:37
【问题描述】:

我配置了

<distributable/>

在 web.xml 中。现在我需要检查 Web 应用程序是否可分发。

我该怎么做?

【问题讨论】:

    标签: java spring-mvc servlets spring-boot cluster-computing


    【解决方案1】:

    您可以从 Tomcat context 获取此信息。您可以将嵌入式 Tomcat 容器定义为 @Bean 并从那里获取。

    import org.apache.catalina.Context;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
    import org.springframework.context.annotation.Bean;
    
    @SpringBootApplication
    public class Application {
    
        private static boolean distributable;
    
        public static boolean getDistributable() {
            return distributable;
        }
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
        @Bean
        public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    
            return new TomcatEmbeddedServletContainerFactory() {
                @Override
                protected void postProcessContext(Context context) {
                    Application.distributable = context.getDistributable();
                    System.out.println("distributable is :"+distributable);
                }
            };
        }   
    }
    

    您可能需要在工厂中以编程方式 setDistributable(true/false) 才能使其正常工作。

    【讨论】:

    • 我如何获取上下文?
    • 谢谢,但我已经完成了这个。我正在寻找一些运行时代码。
    • 公共静态字符串 isDistributable; isDistributable=false(在 tomcat 定制器 bean 中)。并使用 MyClass.isDistributable 访问任何地方。这是您的意思吗?
    • 这给了我正确的答案,但我如何确定应用程序配置是否设置为可分发?有什么方法可以检查我的应用程序是否设置为可分发?这只确保我已将布尔值设置为变量。
    • 实际上我已经在 Application.groovy 上设置了上下文。我在 Grails 3+(Spring 启动应用程序)上。将可分发设置为 true 的对象当然会获得与 true 相同的值(context.setDistributable(true) 和 context.get(Distributable) ---> 相同的对象'context')。所以我正在考虑获取上下文值以不同的方式。
    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 2023-03-22
    • 2021-07-19
    • 1970-01-01
    • 2018-02-20
    • 2018-12-05
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多