[英]Async RabbitMQ communcation using Spring Integration
我有兩個使用 RabbitMQ 進行通信的 Spring Boot 服務。 Service1 向 Service2 發送創建會話的請求。 Service2 處理請求並返回響應。 Service1 應該處理響應。
請求會話的 Service1 方法:
public void startSession()
{
ListenableFuture<SessionCreationResponseDTO> sessionCreationResponse = sessionGateway.requestNewSession();
sessionCreationResponse.addCallback(response -> {
//handle success
}, ex -> {
// handle exception
});
}
在 Service1 上,我定義了 AsyncOutboundGateway,例如:
@Bean
public IntegrationFlow requestSessionFlow(MessageChannel requestNewSessionChannel,
AsyncRabbitTemplate amqpTemplate,
SessionProperties sessionProperties)
{
return flow -> flow.channel(requestNewSessionChannel)
.handle(Amqp.asyncOutboundGateway(amqpTemplate)
.exchangeName(sessionProperties.getRequestSession().getExchangeName())
.routingKey(sessionProperties.getRequestSession().getRoutingKey()));
}
在 Service2 上,我有接收這些消息的流程:
@Bean
public IntegrationFlow requestNewSessionFlow(ConnectionFactory connectionFactory,
SessionProperties sessionProperties,
MessageConverter messageConverter,
RequestNewSessionHandler requestNewSessionHandler)
{
return IntegrationFlows.from(Amqp.inboundGateway(connectionFactory,
sessionProperties.requestSessionProperties().queueName())
.handle(requestNewSessionHandler)
.get();
Service2 處理那里的請求:
@ServiceActivator(async = "true")
public ListenableFuture<SessionCreationResponseDTO> handleRequestNewSession()
{
SettableListenableFuture<SessionCreationResponseDTO> settableListenableFuture = new SettableListenableFuture<>();
// Goes through asynchronous process of creating session and sets value in listenable future
return settableListenableFuture;
}
問題是 Service2 立即將 ListenableFuture 作為消息負載返回給 Service1,而不是等待 future 的結果並返回結果。
如果我理解正確的文檔, 文檔通過設置async參數@ServiceActivator
為true,成功的結果應返回以及異常的情況下,錯誤通道將被使用。
可能我誤解了文檔,因此我需要在將其作為響應返回之前在 Service2 流中解壓 ListenableFuture,但我不確定如何實現。
我嘗試了publishSubscribeChannel
但運氣不佳。
你的問題在這里:
.handle(requestNewSessionHandler)
這樣的配置看不到您的@ServiceActivator(async = "true")
並將其用作常規阻塞服務激活器。
讓我們看看這是否對您有幫助:
.handle(requestNewSessionHandler, "handleRequestNewSession", e -> e.async(true))
最好這樣考慮:或僅注釋配置。 或僅通過 Java DSL 編程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.