首页 > 解决方案 > 我可以将 Spring Event listener 和 Event Publisher 作为单独的应用程序吗?

问题描述

事件发布者应用程序是否可以 24/7 全天候发布事件并且侦听器应用程序每天运行几次以消耗所有事件?

标签: spring-boot

解决方案


有几种方法可以实现您的用例。一种是使用 JMS 队列。假设您创建了两个 Spring Boot 应用程序。

  1. 生产者应用
  2. 消费者应用

只要有任何消息到达,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,您可以利用它来暂停和恢复它。


推荐阅读