spring - 在 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
它注入到.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
向第二个工作进程公开?此外,什么是处理这种事情的好方法?我应该尝试组织我的组件,以便只有相关的组件暴露给工作进程吗?感谢您的关注!
解决方案
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);
}
推荐阅读
- python - 从 Haxe 内部调用外部 Python 类函数
- sql - 给定一个用户 ID,获取他们所有的频道以及收件人和最后的消息预览?
- javascript - 在提交之前在模式页面中显示来自控制器的值
- powershell - Powershell 将文件从一台服务器复制到另一台服务器并使用子字符串重命名
- vb.net - oracle dll更改后当前无法命中断点
- javascript - 如何使用 cypress [cypress] 选择文本
- react-native - 两种颜色的背景 - React Native
- python - Pandas str.replace 跳过一些替换
- ansible - Ansible 标准输出格式
- docker - 弹性连接错误-> Elasticsearch 6 + Kibana + Docker Compose