gpt4 book ai didi

java - Spring Cloud Stream - 应用程序初始化后发送消息

转载 作者:搜寻专家 更新时间:2023-11-01 02:02:23 26 4
gpt4 key购买 nike

我正在尝试使用“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完全初始化消息 channel 后再发送消息呢?

最佳答案

@PostConstruct 触发得太早(在创建配置 bean 时,但在启动上下文和发生绑定(bind)之前)。您想要的是在上下文完全初始化后或至少在输出 channel 绑定(bind)后触发消息的发送。

您有几个选择,都依赖于创建一个额外的 bean:

  1. 要使用 Spring 的 SmartLifecycle 支持(确保 isAutoStartup 默认返回 true 并且阶段为零 -默认 - 这样 bean 在输出绑定(bind)后启动)。

  2. ContextRefreshedEvent 使用 ApplicationListener

  3. 由于这是一个 Spring Boot 应用程序,您可以使用 ApplicationRunner bean(在创建上下文后调用它)。

关于java - Spring Cloud Stream - 应用程序初始化后发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com