MessagingTemplate

当引入端点及其各种配置选项后,Spring 集成会为消息传递组件提供一个基础,以便从消息传递系统中非侵入性地调用您的应用程序代码。但是,有时需要从您的应用程序代码中调用消息传递系统。为了方便实现此类用例,Spring 集成提供了一个 MessagingTemplate,它支持跨消息通道的各种操作,包括请求和答复方案。例如,可以发送请求并等待答复,如下所示:

When the endpoints and their various configuration options are introduced, Spring Integration provides a foundation for messaging components that enables non-invasive invocation of your application code from the messaging system. However, it is sometimes necessary to invoke the messaging system from your application code. For convenience when implementing such use cases, Spring Integration provides a MessagingTemplate that supports a variety of operations across the message channels, including request and reply scenarios. For example, it is possible to send a request and wait for a reply, as follows:

MessagingTemplate template = new MessagingTemplate();

Message reply = template.sendAndReceive(someChannel, new GenericMessage("test"));

在上述示例中,模板将在内部创建一个临时匿名通道。还可以在模板上设置“发送超时”和“接收超时”属性,并且还支持其他交换类型。以下列表显示了此类方法的签名:

In the preceding example, a temporary anonymous channel would be created internally by the template. The 'sendTimeout' and 'receiveTimeout' properties may also be set on the template, and other exchange types are also supported. The following listing shows the signatures for such methods:

public boolean send(final MessageChannel channel, final Message<?> message) { ...
}

public Message<?> sendAndReceive(final MessageChannel channel, final Message<?> request) { ...
}

public Message<?> receive(final PollableChannel<?> channel) { ...
}

xref:gateway.adoc#gateway-proxy[Enter the GatewayProxyFactoryBean 中描述了一种侵入性较小的方法,它允许你使用有效负载或头值调用简单接口,而不是 Message 实例。

A less invasive approach that lets you invoke simple interfaces with payload or header values instead of Message instances is described in Enter the GatewayProxyFactoryBean.