[英]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:
要使用Spring的SmartLifecycle
支持(確保isAutoStartup
默認返回true
且相位為零 - 默認值 - 以便在綁定輸出后啟動bean)。
對ContextRefreshedEvent
使用ApplicationListener
。
由於這是一個Spring Boot應用程序,因此您可以使用ApplicationRunner
bean(在創建上下文后調用它)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.