【问题标题】:Implementing worker processes in a Spring Boot application在 Spring Boot 应用程序中实现工作进程
【发布时间】:2021-05-19 14:01:45
【问题描述】:

简介

我目前正在单个网络测功机上通过 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();
    }
}

在运行上面的 sn-p 时,我得到一个不满意的 bean MongoTemplate 依赖错误,我将它注入到 UProductRepository 的具体实现中,称为 UProductRepositoryImpl

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 暴露给第二个工作进程?此外,什么是处理这种事情的好方法?我应该尝试组织我的组件,以便只有相关的组件暴露给工作进程吗?感谢您的关注!

【问题讨论】:

    标签: spring spring-boot heroku spring-data-mongodb worker


    【解决方案1】:

    解决方案

    由于工作进程也必须是一个 Spring 应用程序(为了允许注入存储库等),所以它的应用程序上下文必须这样初始化。 web 参数是为了防止设置正确的 web 服务器,因为这不是必需的。

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

    【讨论】:

      猜你喜欢
      • 2019-08-17
      • 2018-06-25
      • 2017-11-11
      • 2017-01-19
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多