首页 > 解决方案 > 在 Spring Boot 应用程序中实现工作进程

问题描述

介绍

我目前正在单个网络测功机上通过 Heroku 运行 Spring-Boot 应用程序。由于大量密集的后台任务(从 3rd 方 API 获取资源、发送邮件等),我想将所有这些“繁重的工作”转移到第二个工作人员测功机/进程上。但是,在将应用程序组件(例如@Repositories)正确地暴露给第二个工作进程时,我面临着一些困难。

到目前为止我所做的尝试

我创建了第二个主类 ( BackgroundWorker),我在 Procfile 中将其指定为工作进程。然后调用以下类以初始化后台任务。

@Service
@EnableMongoRepositories("com.a.viz.db")
@ComponentScan("com.a.viz.db")
@EntityScan("com.a.viz.model")
public class TaskHandler {
    @Autowired
    UProductRepository productRepository;

    public void initScheduler()
    {
        Runnable fetchProducts = () -> {
            Scheduler.fetchProducts(productRepository);
        };
    }
}

虽然主类看起来像这样:

public class BackgroundWorker {
    static Logger logger =  LoggerFactory.getLogger(BackgroundWorker.class);

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.scan("com.a.viz.workers");
        context.refresh();
        TaskHandler handler = context.getBean(TaskHandler.class);
        handler.initScheduler();
    }
}

运行上面的代码片段后,我得到了一个不满意的 bean 依赖错误,我将MongoTemplate它注入到.UProductRepositoryUProductRepositoryImpl

public class UProductRepositoryImpl implements UProductRepositoryCustom {
    private final MongoTemplate mongoTemplate;

    @Autowired
    public UProductRepositoryImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
}

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.MongoTemplate'

我如何MongoTemplate向第二个工作进程公开?此外,什么是处理这种事情的好方法?我应该尝试组织我的组件,以便只有相关的组件暴露给工作进程吗?感谢您的关注!

标签: springspring-bootherokuspring-data-mongodbworker

解决方案


Solution

Since the worker process must also be a Spring application (in order to allow for injecting repositories and such), its application context must be initialized as such. The web parameter is to prevent a proper web server being set up, since that is not necessary.

// Other configs..
@EnableAutoConfiguration
public class BackgroundWorker implements ApplicationRunner {

    @Autowired
    // Repositories..

    public static void main(String[] args)
    {
        new SpringApplicationBuilder(BackgroundWorker.class)
                .web(WebApplicationType.NONE)
                .run(args);
    }

推荐阅读