首页 > 解决方案 > Spring Integration - 具有返回值的消息传递网关

问题描述

我是 Spring Integration 的新手。我需要实现一个带有返回值的消息网关。为了在执行一些同步步骤后继续异步处理。所以我做了2个激活器

@Slf4j
@MessageEndpoint
public class Activator1 {

@ServiceActivator(inputChannel = "asyncChannel")
public void async(){
    log.info("Just async message");
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        log.error("I don't want to sleep now");
    }
}
}

@Slf4j
@MessageEndpoint
public class Activator2 {

@ServiceActivator(inputChannel = "syncChannel")
public ResponseEntity sync(){
    try {
        Thread.sleep(500);
        return ResponseEntity.ok("Return Http Message");
    } catch (InterruptedException e) {
        log.error("I don't want to sleep");
    }
    return ResponseEntity.badRequest().build();
}
}

管道

@Configuration
public class Pipeline {

@Bean
MessageChannel asyncChannel() {
    return new DirectChannel();
}

@Bean
public MessageChannel syncChannel() {
    return MessageChannels.direct().get();
}

}

网关

@MessagingGateway
public interface ReturningGateway {

@Gateway(requestChannel = "asyncChannel", replyChannel = "syncChannel")
public ResponseEntity getSyncHttpResponse();

}

和控制器

@Slf4j
@RestController
@RequestMapping("/sync")
public class ResponseController {

@Autowired
ReturningGateway returningGateway;

@PostMapping("/http-response")
public ResponseEntity post() {
    
    return returningGateway.getSyncHttpResponse();
    
}
}

所以我不确定这是否是做我想做的事情的正确方法

你能把手给我吗?

标签: spring-integration

解决方案


让我首先尝试解释一些事情!

@Gateway(requestChannel = "asyncChannel", replyChannel = "syncChannel")

requestChannel是网关发送消息的地方。但是由于您在网关方法中没有任何参数并且没有 a payloadExpression,因此行为是从该通道“接收”。有关更多信息,请参阅文档:https ://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints.html#gateway-calling-no-argument-methods 。

replyChannel是等待回复而不是发送的地方。在大多数情况下,网关依赖replyChannel标头进行关联。消息传递中的请求-答复模式。replyChannel如果PublishSubscribeChannel以某种方式跟踪回复或者当我们处理我们无法修改以依赖标头的流时,我们需要一个显式的replyChannel。请参阅文档中的相同网关章节。

你的用例对我来说不是很清楚:你说的是async延续,但同时你的网关合约的回报看起来像是该sync()方法的结果。从这里开始,请让自己熟悉网关合约,然后以全新的愿景与您的解决方案联系我们。


推荐阅读