【问题标题】:How to initialize SpringContext once and share across tasks?如何初始化一次 SpringContext 并跨任务共享?
【发布时间】:2017-12-01 14:33:46
【问题描述】:

我正在尝试在我的 Spark 应用程序中初始化 spring 上下文。我想要我的从节点中的上下文以及我想要重用 bean。这是相同的代码:-

shipperRD2.foreach(shipper->{

 AmazonS3 amazonS3Client = AmazonS3ClientBuilder.standard().build();
                    FileSystemXmlApplicationContext context2 = new FileSystemXmlApplicationContext("https://s3.console.aws.amazon.com/s3/object/spring-configuration/app-context.xml");

PersistenceWrapper persistenceWrapper = context.getBean(PersistenceWrapper.class);
});

但是,这会导致每次在从节点上运行新任务时都会刷新上下文。有什么办法可以避免这种行为。基本上,只需在第一个任务运行时初始化上下文,并在后续任务中重新使用该上下文。

【问题讨论】:

  • 您是否尝试过单例(反)模式或使用广播变量?
  • 将尝试单例模式。广播变量应该是可序列化的,所以在这里不适用。

标签: spring apache-spark spring-bean spring-config


【解决方案1】:

正如 Jacek 所说,我尝试了单例模式,并且成功了。

public class SpringInit {

    private static FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(fileName);

    private SpringInit(){
    }

    public static FileSystemXmlApplicationContext getInstance(){
        return context;
    }
 }

来自火花,

shipperRD2.foreach(shipper->{

  FileSystemXmlApplicationContext context = SpringInit.getInstance();
PersistenceWrapper persistenceWrapper = context.getBean(PersistenceWrapper.class);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多