簡體   English   中英

Spring雲流 - 應用初始化后發送消息

[英]Spring cloud stream - send message after application initalization

我試圖使用“spring cloud stream”向rabbitmq發送一條簡單的消息。 基本上代碼看起來像這樣:

@EnableBinding(Source.class)
@SpringBootApplication
public class SourceApplication {

    public static void main(String[] args) {
        SpringApplication.run(SourceApplication.class, args);
    }

    @Autowired Source source;

    @PostConstruct
    public void init() {
        source.send(MessageBuilder.withPayload("payload").build());
    }
}

然后我收到此錯誤消息:

org.springframework.messaging.MessageDeliveryException: Dispatcher has no subscribers for channel 'unknown.channel.name'.; nested exception is org.springframework.integration.MessageDispatchingException: Dispatcher has no subscribers, failedMessage=GenericMessage [payload=******, headers={id=c60dd5be-6576-99d5-fd1b-b1cb94c191c1, timestamp=1488651422892}]
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:93)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:423)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)

但是,如果我添加一些延遲,在發送消息(只是第二個或幾個)之前,它可以正常工作。 我的問題是:如何在Spring完全初始化消息通道然后發送消息之前等待?

@PostConstruct過早觸發(在創建配置bean時,但在上下文啟動並發生綁定之前)。 您想要的是在上下文完全初始化后觸發消息的發送,或者至少在綁定輸出通道之后觸發。

你有幾個選擇,都依賴於創建一個額外的bean:

  1. 要使用Spring的SmartLifecycle支持(確保isAutoStartup默認返回true且相位為零 - 默認值 - 以便在綁定輸出后啟動bean)。

  2. ContextRefreshedEvent使用ApplicationListener

  3. 由於這是一個Spring Boot應用程序,因此您可以使用ApplicationRunner bean(在創建上下文后調用它)。

您可以查看Spring的Task Execution和Scheduling功能

特別是,聽起來你想要的是34.4節所涵蓋的內容

另外,我發現了類似問題的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM