Web 服务支持

本章介绍了 Spring Integration 对 Web 服务的支持,包括

项目需要此依赖项

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-ws</artifactId>
    <version>7.0.0</version>
</dependency>
compile "org.springframework.integration:spring-integration-ws:7.0.0"

出站 Web 服务网关

当您向通道发送消息时调用 Web 服务,您有两个选项,两者都基于 Spring Web Services 项目:SimpleWebServiceOutboundGatewayMarshallingWebServiceOutboundGateway。前者接受 Stringjavax.xml.transform.Source 作为消息负载。后者支持 MarshallerUnmarshaller 接口的任何实现。两者都需要一个 Spring Web Services DestinationProvider,以确定要调用的 Web 服务的 URI。以下示例显示了调用 Web 服务的两种选项

 simpleGateway = new SimpleWebServiceOutboundGateway(destinationProvider);

 marshallingGateway = new MarshallingWebServiceOutboundGateway(destinationProvider, marshaller);
使用命名空间支持(稍后描述)时,您只需设置一个 URI。在内部,解析器会配置一个固定的 URI DestinationProvider 实现。但是,如果您需要在运行时动态解析 URI,那么 DestinationProvider 可以提供从注册表查找 URI 等行为。有关此策略的更多信息,请参阅 Spring Web Services DestinationProvider Javadoc。

从 5.0 版开始,您可以为 SimpleWebServiceOutboundGatewayMarshallingWebServiceOutboundGateway 提供一个外部 WebServiceTemplate 实例,您可以为任何自定义属性配置该实例,包括 checkConnectionForFault(它允许您的应用程序处理不符合规范的服务)。

有关内部工作原理的更多详细信息,请参阅 Spring Web Services 参考指南中关于客户端访问的章节以及关于对象/XML 映射的章节。

入站 Web 服务网关

要在收到 Web 服务调用时向通道发送消息,您同样有两个选项:SimpleWebServiceInboundGatewayMarshallingWebServiceInboundGateway。前者从 WebServiceMessage 中提取 javax.xml.transform.Source 并将其设置为消息负载。后者支持 MarshallerUnmarshaller 接口的实现。如果传入的 Web 服务消息是 SOAP 消息,则 SOAP 动作头将添加到转发到请求通道的 Message 的头中。以下示例显示了这两个选项

 simpleGateway = new SimpleWebServiceInboundGateway();
 simpleGateway.setRequestChannel(forwardOntoThisChannel);
 simpleGateway.setReplyChannel(listenForResponseHere); //Optional

 marshallingGateway = new MarshallingWebServiceInboundGateway(marshaller);
 //set request and optionally reply channel

这两个网关都实现了 Spring Web Services MessageEndpoint 接口,因此可以按照标准 Spring Web Services 配置将其与 MessageDispatcherServlet 一起配置。

有关如何使用这些组件的更多详细信息,请参阅 Spring Web Services 参考指南中关于创建 Web 服务的章节。关于对象/XML 映射的章节也再次适用。

要将 SimpleWebServiceInboundGatewayMarshallingWebServiceInboundGateway 配置添加到 Spring WS 基础设施中,您应该在 MessageDispatcherServlet 和目标 MessageEndpoint 实现之间添加 EndpointMapping 定义,就像您对普通的 Spring WS 应用程序一样。为此(从 Spring Integration 的角度来看),Spring WS 提供了以下方便的 EndpointMapping 实现

  • o.s.ws.server.endpoint.mapping.UriEndpointMapping

  • o.s.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping

  • o.s.ws.soap.server.endpoint.mapping.SoapActionEndpointMapping

  • o.s.ws.server.endpoint.mapping.XPathPayloadEndpointMapping

您必须在应用程序上下文中指定这些类的 bean,并根据 WS 映射算法引用 SimpleWebServiceInboundGateway 和/或 MarshallingWebServiceInboundGateway bean 定义。

有关更多信息,请参阅端点映射

Web 服务命名空间支持

要配置出站 Web 服务网关,请使用 ws 命名空间中的 outbound-gateway 元素,如以下示例所示

<int-ws:outbound-gateway id="simpleGateway"
                     request-channel="inputChannel"
                     uri="https://example.org"/>
此示例不提供“reply-channel”。如果 Web 服务返回非空响应,则包含该响应的 Message 将发送到请求消息的 REPLY_CHANNEL 头中定义的回复通道。如果不可用,则抛出通道解析异常。如果您想将回复发送到另一个通道,请在“outbound-gateway”元素上提供一个“reply-channel”属性。
默认情况下,当您使用 String 负载的请求 Message 调用 Web 服务后,如果 Web 服务返回空响应,则不会发送回复 Message。因此,您不需要设置“reply-channel”或在请求 Message 中包含 REPLY_CHANNEL 头。如果您确实希望将空响应作为 Message 接收,可以将“ignore-empty-responses”属性设置为 false。这样做仅适用于 String 对象,因为使用 SourceDocument 对象会导致空响应,从而永远不会生成回复 Message

要设置入站 Web 服务网关,请使用 inbound-gateway 元素,如以下示例所示

<int-ws:inbound-gateway id="simpleGateway"
                    request-channel="inputChannel"/>

要使用 Spring OXM 编组器或解组器,您必须提供 bean 引用。以下示例显示了如何为出站编组网关提供 bean 引用

<int-ws:outbound-gateway id="marshallingGateway"
                     request-channel="requestChannel"
                     uri="https://example.org"
                     marshaller="someMarshaller"
                     unmarshaller="someUnmarshaller"/>

以下示例显示了如何为入站编组网关提供 bean 引用

<int-ws:inbound-gateway id="marshallingGateway"
                    request-channel="requestChannel"
                    marshaller="someMarshaller"
                    unmarshaller="someUnmarshaller"/>
大多数 Marshaller 实现也实现了 Unmarshaller 接口。当使用这样的 Marshaller 时,只需 marshaller 属性。即使使用 Marshaller,您也可以为出站网关上的 request-callback 提供引用。

对于任何一种出站网关类型,您可以指定 destination-provider 属性而不是 uri(两者中正好需要一个)。然后您可以引用任何 Spring Web Services DestinationProvider 实现(例如,在运行时从注册表查找 URI)。

对于任何一种出站网关类型,message-factory 属性也可以配置为引用任何 Spring Web Services WebServiceMessageFactory 实现。

对于简单入站网关类型,您可以将 extract-payload 属性设置为 false,以将整个 WebServiceMessage 而不是仅将其负载作为 Message 转发到请求通道。例如,当自定义转换器直接对 WebServiceMessage 进行操作时,这可能很有用。

从 5.0 版本开始,web-service-template 引用属性允许您注入一个具有任何可能自定义属性的 WebServiceTemplate

Web 服务 Java DSL 支持

Web 服务命名空间支持中所示的网关的等效配置显示在以下代码片段中

@Bean
IntegrationFlow inbound() {
    return IntegrationFlow.from(Ws.simpleInboundGateway()
                .id("simpleGateway"))
        ...
        .get();
}
@Bean
IntegrationFlow outboundMarshalled() {
    return f -> f.handle(Ws.marshallingOutboundGateway()
                    .id("marshallingGateway")
                    .marshaller(someMarshaller())
                    .unmarshaller(someUnmarshalller()))
        ...
}
@Bean
IntegrationFlow inboundMarshalled() {
    return IntegrationFlow.from(Ws.marshallingInboundGateway()
                .marshaller(someMarshaller())
                .unmarshaller(someUnmarshalller())
                .id("marshallingGateway"))
        ...
        .get();
}

其他属性可以通过流畅的方式在端点规范上设置(这些属性取决于是否已为出站网关提供了外部 WebServiceTemplate)。例如

.from(Ws.simpleInboundGateway()
                .extractPayload(false))
.handle(Ws.simpleOutboundGateway(template)
            .uri(uri)
            .sourceExtractor(sourceExtractor)
            .encodingMode(DefaultUriBuilderFactory.EncodingMode.NONE)
            .headerMapper(headerMapper)
            .ignoreEmptyResponses(true)
            .requestCallback(requestCallback)
            .uriVariableExpressions(uriVariableExpressions)
            .extractPayload(false))
)
.handle(Ws.marshallingOutboundGateway()
            .destinationProvider(destinationProvider)
            .marshaller(marshaller)
            .unmarshaller(unmarshaller)
            .messageFactory(messageFactory)
            .encodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY)
            .faultMessageResolver(faultMessageResolver)
            .headerMapper(headerMapper)
            .ignoreEmptyResponses(true)
            .interceptors(interceptor)
            .messageSenders(messageSender)
            .requestCallback(requestCallback)
            .uriVariableExpressions(uriVariableExpressions))
.handle(Ws.marshallingOutboundGateway(template)
            .uri(uri)
            .encodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT)
            .headerMapper(headerMapper)
            .ignoreEmptyResponses(true)
            .requestCallback(requestCallback)
            .uriVariableExpressions(uriVariableExpressions))
)

出站 URI 配置

对于 Spring Web Services 支持的所有 URI 方案(请参阅URI 和传输),都提供了 <uri-variable/> 替换。以下示例展示了如何定义它

<ws:outbound-gateway id="gateway" request-channel="input"
        uri="https://springsource.org/{thing1}-{thing2}">
    <ws:uri-variable name="thing1" expression="payload.substring(1,7)"/>
    <ws:uri-variable name="thing2" expression="headers.x"/>
</ws:outbound-gateway>

<ws:outbound-gateway request-channel="inputJms"
        uri="jms:{destination}?deliveryMode={deliveryMode}&amp;priority={priority}"
        message-sender="jmsMessageSender">
    <ws:uri-variable name="destination" expression="headers.jmsQueue"/>
    <ws:uri-variable name="deliveryMode" expression="headers.deliveryMode"/>
    <ws:uri-variable name="priority" expression="headers.jms_priority"/>
</ws:outbound-gateway>

如果您提供 DestinationProvider,则不支持变量替换,并且如果您提供变量,则会发生配置错误。

控制 URI 编码

默认情况下,URL 字符串在发送请求之前被编码(请参阅UriComponentsBuilder)为 URI 对象。在某些非标准 URI 的情况下,执行编码是不希望的。<ws:outbound-gateway/> 元素提供了一个 encoding-mode 属性。要禁用 URL 编码,请将此属性设置为 NONE(默认情况下,它为 TEMPLATE_AND_VALUES)。如果您希望部分编码某些 URL,可以通过在 <uri-variable/> 中使用 expression 来实现,如以下示例所示

<ws:outbound-gateway url="https://somehost/%2f/someApps?someKey={param}" encoding-mode="NONE">
          <http:uri-variable name="param"
            expression="T(org.apache.commons.httpclient.util.URIUtil)
                                             .encodeWithinQuery('Hello World!')"/>
</ws:outbound-gateway>
如果您设置了 DestinationProviderencoding-mode 将被忽略。

WS 消息头

Spring Integration Web 服务网关会自动映射 SOAP 动作头。默认情况下,它通过使用 DefaultSoapHeaderMapper 在 Spring Integration MessageHeaders 之间复制。

您可以传入您自己实现的 SOAP 特定头映射器,因为网关具有支持这样做的属性。

除非 DefaultSoapHeaderMapperrequestHeaderNamesreplyHeaderNames 属性明确指定,否则任何用户定义的 SOAP 标头都不会复制到 SOAP 消息或从 SOAP 消息复制。

当您使用 XML 命名空间进行配置时,您可以使用 mapped-request-headersmapped-reply-headers 属性设置这些属性,您可以通过设置 header-mapper 属性提供自定义映射器。

在映射用户定义头时,值也可以包含简单的通配符模式(例如 myheader***myheader**)。例如,如果您需要复制所有用户定义头,可以使用通配符:*

从 4.1 版开始,AbstractHeaderMapperDefaultSoapHeaderMapper 的超类)允许为 requestHeaderNamesreplyHeaderNames 属性配置 NON_STANDARD_HEADERS 令牌(除了现有的 STANDARD_REQUEST_HEADERSSTANDARD_REPLY_HEADERS)以映射所有用户定义的头。

我们建议使用以下组合:STANDARD_REPLY_HEADERS, NON_STANDARD_HEADERS,而不是使用通配符(*)。这样做可以避免将 request 标头映射到回复。

从 4.3 版开始,您可以通过在模式前加上 ! 来否定标头映射中的模式。否定模式具有优先级,因此像 STANDARD_REQUEST_HEADERS,thing1,thing*,!thing2,!thing3,thing5,!thing1 这样的列表不映射 thing1thing2thing3。它映射标准标头、thing4thing5。(请注意,thing1 同时包含在非否定形式和否定形式中。由于否定值优先,因此 thing1 不会被映射。)

如果您有一个以 ! 开头的用户定义头,并且您希望对其进行映射,您可以使用 \ 对其进行转义,如下所示:STANDARD_REQUEST_HEADERS,\!myBangHeader。然后 !myBangHeader 将被映射。

入站 SOAP 头(入站网关的请求头和出站网关的回复头)被映射为 SoapHeaderElement 对象。您可以通过访问 Source 来查看其内容

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <auth>
            <username>user</username>
            <password>pass</password>
        </auth>
        <cat>CAT</cat>
        <can>CAN</can>
        <dog>DOG</dog>
    </soapenv:Header>
    <soapenv:Body>
        ...
    </soapenv:Body>
</soapenv:Envelope>

如果 mapped-request-headersauth, ca*,则 authcatcan 头将被映射,但 dog 不会被映射。

以下示例展示了如何从名为 auth 的头中获取名为 user 的值

...
SoapHeaderElement header = (SoapHeaderElement) headers.get("auth");
DOMSource source = (DOMSource) header.getSource();
NodeList nodeList = source.getNode().getChildNodes();
assertEquals("username", nodeList.item(0).getNodeName());
assertEquals("user", nodeList.item(0).getFirstChild().getNodeValue());
...

从 5.0 版本开始,DefaultSoapHeaderMapper 支持类型为 javax.xml.transform.Source 的用户定义头,并将其填充为 <soapenv:Header> 的子节点。以下示例展示了如何实现这一点

Map<String, Object> headers = new HashMap<>();

String authXml =
     "<auth xmlns='http://test.auth.org'>"
           + "<username>user</username>"
           + "<password>pass</password>"
           + "</auth>";
headers.put("auth", new StringSource(authXml));
...
DefaultSoapHeaderMapper mapper = new DefaultSoapHeaderMapper();
mapper.setRequestHeaderNames("auth");

以上示例的结果是以下 SOAP 信封

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <auth xmlns="http://test.auth.org">
            <username>user</username>
            <password>pass</password>
        </auth>
    </soapenv:Header>
    <soapenv:Body>
        ...
    </soapenv:Body>
</soapenv:Envelope>

MTOM 支持

编组入站和出站 Web 服务网关直接通过编组器的内置功能(例如,Jaxb2Marshaller 提供了 mtomEnabled 选项)支持附件。从 5.0 版本开始,简单 Web 服务网关可以直接操作入站和出站 MimeMessage 实例,这些实例具有操作附件的 API。当您需要发送带有附件的 Web 服务消息(无论是来自服务器的回复还是客户端请求)时,您应该直接使用 WebServiceMessageFactory,并将带有附件的 WebServiceMessage 作为 payload 发送到网关的请求或回复通道。以下示例展示了如何实现这一点

WebServiceMessageFactory messageFactory = new SaajSoapMessageFactory(MessageFactory.newInstance());
MimeMessage webServiceMessage = (MimeMessage) messageFactory.createWebServiceMessage();

String request = "<test>test data</test>";

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new StringSource(request), webServiceMessage.getPayloadResult());

webServiceMessage.addAttachment("myAttachment", new ByteArrayResource("my_data".getBytes()), "plain/text");

this.webServiceChannel.send(new GenericMessage<>(webServiceMessage));
© . This site is unofficial and not affiliated with VMware.