spring-boot - 我可以将 Spring Event listener 和 Event Publisher 作为单独的应用程序吗?
问题描述
事件发布者应用程序是否可以 24/7 全天候发布事件并且侦听器应用程序每天运行几次以消耗所有事件?
解决方案
有几种方法可以实现您的用例。一种是使用 JMS 队列。假设您创建了两个 Spring Boot 应用程序。
- 生产者应用
- 消费者应用
只要有任何消息到达,producer-app 就会将消息写入队列。下面是一个小代码片段,它说明了我的意思: -
@PostMapping(path = "/object", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity writeObject(@RequestBody String requestPayload) {
try {
// This wil put the message to the queue.
jmsTemplate.send("queue-name", mapper.writeValueAsString(requestPayload));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
return ResponseEntity.status(HttpStatus.OK).build();
}
另一方面,我们有消费者应用程序,它将定期进行轮询,并从队列中读取消息:-
@JmsListener(destination="queue-name",
containerFactory="facotryName", id="id", concurrency="1-2")
public void receiveMessage(ActiveMQTextMessage message) throws Throwable
{
try {
// read message here
} catch (Throwable e) {
}
}
此消费者应用程序将配置 JmsListener,它将在预定时间启动。有一个可用的 bean JmsListenerEndpointRegistry,您可以利用它来暂停和恢复它。
推荐阅读
- mysql - 我在 MySQL 中的查询没有得到预期的结果
- arrays - 将其内容向后复制到另一个数组的数组无法正常工作
- c - LZW序列实现
- sumo - 如何从 Webots 中的 Highway_overtake.py 访问 SUMO 车辆?
- java - 如何定义一个构造函数来为每个数组调用它?
- c# - AcquireTokenAsync 为图形客户端库中的用户凭据返回 401(未授权)
- amazon-web-services - AWS boto3 - 如何运行现货实例?
- sql - 我需要根据SSMS中相同条件的相同数据位置的19列返回行
- authentication - 如果两个 API 使用不同的身份提供者,一个 API 如何使用 oauth2 调用另一个 API?
- odata - 如何根据父类型的属性使用嵌套类型的过滤器正确查询 OData?