跳到主要内容

HTTP 命名空间支持

QWen Plus 中英对照 HTTP Namespace Support

Spring Integration 提供了一个 http 命名空间以及相应的模式定义。要将其包含在配置中,在应用程序上下文配置文件中提供以下命名空间声明:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
https://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/http
https://www.springframework.org/schema/integration/http/spring-integration-http.xsd">
...
</beans>
xml

入站

XML 命名空间提供了两个组件来处理 HTTP 入站请求:inbound-channel-adapterinbound-gateway。为了在不返回专用响应的情况下处理请求,使用 inbound-channel-adapter。以下示例展示了如何配置一个:

<int-http:inbound-channel-adapter id="httpChannelAdapter" channel="requests"
supported-methods="PUT, DELETE"/>
xml

要处理确实期望响应的请求,请使用 inbound-gateway。以下示例展示了如何配置一个:

<int-http:inbound-gateway id="inboundGateway"
request-channel="requests"
reply-channel="responses"/>
xml

请求映射支持

备注

Spring Integration 3.0 通过引入 IntegrationRequestMappingHandlerMapping 改进了 REST 支持。该实现依赖于 Spring Framework 3.1 或更高版本提供的增强型 REST 支持。

HTTP 入口网关或 HTTP 入口通道适配器的解析会注册一个类型为 IntegrationRequestMappingHandlerMappingintegrationRequestMappingHandlerMapping bean,如果尚未注册的话。这个特定的 HandlerMapping 实现将其逻辑委托给 RequestMappingInfoHandlerMapping。该实现提供了类似于 Spring MVC 中 org.springframework.web.bind.annotation.RequestMapping 注解的功能。

备注

有关更多信息,请参阅 使用 @RequestMapping 映射请求

为此,Spring Integration 3.0 引入了 <request-mapping> 元素。你可以将这个可选元素添加到 <http:inbound-channel-adapter><http:inbound-gateway> 中。它与 pathsupported-methods 属性协同工作。以下示例展示了如何在入站网关上配置它:

<inbound-gateway id="inboundController"
request-channel="requests"
reply-channel="responses"
path="/foo/{fooId}"
supported-methods="GET"
view-name="foo"
error-code="oops">
<request-mapping headers="User-Agent"
params="myParam=myValue"
consumes="application/json"
produces="!text/plain"/>
</inbound-gateway>
xml

基于上述配置,命名空间解析器会创建一个 IntegrationRequestMappingHandlerMapping 实例(如果不存在的话)和一个 HttpRequestHandlingController bean,并将其与一个 RequestMapping 实例关联。这个 RequestMapping 实例随后会被转换为 Spring MVC 的 RequestMappingInfo

<request-mapping> 元素提供以下属性:

  • headers

  • params

  • consumes

  • produces

通过 <http:inbound-channel-adapter><http:inbound-gateway>pathsupported-methods 属性,以及 <request-mapping> 属性,可以直接翻译成 Spring MVC 中 org.springframework.web.bind.annotation.RequestMapping 注解提供的相应选项。

<request-mapping> 元素允许你将多个 Spring Integration HTTP 入站端点配置到相同的 path(甚至相同的 supported-methods),并根据传入的 HTTP 请求提供不同的下游消息流。

或者,你也可以只声明一个 HTTP 入站端点,并在 Spring Integration 流中应用路由和过滤逻辑以达到相同的效果。这让你可以尽可能早地将 Message 引入流中。以下示例展示了如何做到这一点:

<int-http:inbound-gateway request-channel="httpMethodRouter"
supported-methods="GET,DELETE"
path="/process/{entId}"
payload-expression="#pathVariables.entId"/>

<int:router input-channel="httpMethodRouter" expression="headers.http_requestMethod">
<int:mapping value="GET" channel="in1"/>
<int:mapping value="DELETE" channel="in2"/>
</int:router>

<int:service-activator input-channel="in1" ref="service" method="getEntity"/>

<int:service-activator input-channel="in2" ref="service" method="delete"/>
xml

有关处理器映射的更多信息,请参阅 Spring Framework Web Servlet 文档Spring Framework Web Reactive 文档

important

IntegrationRequestMappingHandlerMapping 扩展了 Spring MVC 的 RequestMappingHandlerMapping 类,继承了其大部分逻辑,特别是 handleNoMatch(Set, String, HttpServletRequest),当映射因某种原因不匹配时,它会抛出一个特定的 4xx 错误用于 HTTP 响应,防止调用应用程序上下文中的任何剩余映射处理程序。因此,为 Spring Integration 和 Spring MVC 请求映射配置相同的路径(例如,在一个中配置 POST,在另一个中配置 GET)是不支持的;MVC 映射将不会被找到。

跨源资源共享 (CORS) 支持

从 4.2 版本开始,您可以使用 <cross-origin> 元素配置 <http:inbound-channel-adapter><http:inbound-gateway>。它表示与 Spring MVC 的 @CrossOrigin 用于 @Controller 注解相同的选项,并允许为 Spring Integration HTTP 端点配置跨源资源共享 (CORS):

  • origin: 允许的来源列表。* 表示允许所有来源。这些值会被放置在预检请求和实际响应的 Access-Control-Allow-Origin 响应头中。默认值是 *

  • allowed-headers: 指示在实际请求中可以使用哪些请求头。* 表示允许客户端请求的所有头部。此属性控制预检响应的 Access-Control-Allow-Headers 响应头的值。默认值是 *

  • exposed-headers: 用户代理允许客户端访问的响应头列表。此属性控制实际响应的 Access-Control-Expose-Headers 响应头的值。

  • method: 允许的 HTTP 请求方法:GETPOSTHEADOPTIONSPUTPATCHDELETETRACE。这里指定的方法会覆盖 supported-methods 中的方法。

  • allow-credentials: 如果设置为 true,浏览器应该包含与请求域关联的任何 cookie;如果设置为 false,则不应包含。空字符串 ("") 表示未定义。如果为 true,预检响应将包含 Access-Control-Allow-Credentials=true 响应头。默认值是 true

  • max-age: 控制预检响应的缓存持续时间。将其设置为合理的值可以减少浏览器所需的预检请求 - 响应交互次数。此属性控制预检响应中的 Access-Control-Max-Age 响应头的值。值为 -1 表示未定义。默认值是 1800 秒(30 分钟)。

CORS Java 配置由 org.springframework.integration.http.inbound.CrossOrigin 类表示,该类的实例可以注入到 HttpRequestHandlingEndpointSupport beans 中。

响应状态码

从 4.1 版本开始,您可以使用 status-code-expression 配置 <http:inbound-channel-adapter> 以覆盖默认的 200 OK 状态。表达式必须返回一个可以转换为 org.springframework.http.HttpStatus 枚举值的对象。evaluationContext 包含一个 BeanResolver,并且从 5.1 版本开始,它以根对象的形式提供 RequestEntity<?>。一个例子可能是解析一些在运行时返回状态码值的作用域 bean。然而,更可能的是,它被设置为固定值,例如 status-code=expression="204"(无内容),或 status-code-expression="T(org.springframework.http.HttpStatus).NO_CONTENT"。默认情况下,status-code-expression 为 null,这意味着返回正常的 '200 OK' 响应状态。使用 RequestEntity<?> 作为根对象,状态码可以根据请求方法、某些标头、URI 内容甚至请求体进行条件判断。以下示例展示了如何将状态码设置为 ACCEPTED

<http:inbound-channel-adapter id="inboundController"
channel="requests" view-name="foo" error-code="oops"
status-code-expression="T(org.springframework.http.HttpStatus).ACCEPTED">
<request-mapping headers="BAR"/>
</http:inbound-channel-adapter>
xml

<http:inbound-gateway> 从回复 Messagehttp_statusCode 头中解析 '状态码'。从 4.2 版本开始,默认的响应状态码在未在 reply-timeout 内收到回复时是 500 Internal Server Error。有两种方式可以修改此行为:

  • 添加一个 reply-timeout-status-code-expression。这与入站适配器上的 status-code-expression 具有相同的语义。

  • 添加一个 error-channel 并返回带有 HTTP 状态码头的适当消息,如下例所示:

    <int:chain input-channel="errors">
    <int:header-enricher>
    <int:header name="http_statusCode" value="504" />
    </int:header-enricher>
    <int:transformer expression="payload.failedMessage" />
    </int:chain>
    xml

ErrorMessage 的有效负载是 MessageTimeoutException。它必须转换为网关可以转换的内容,例如 String。一个很好的候选是异常的 message 属性,这就是在使用 expression 技术时所用的值。

如果错误流在主流超时后超时,返回 500 Internal Server Error ,或者,如果存在 reply-timeout-status-code-expression ,则会对其进行评估。

备注

之前,超时的默认状态码是 200 OK。要恢复该行为,请设置 reply-timeout-status-code-expression="200"

从 5.4 版本开始,准备请求消息时遇到的错误会被发送到错误通道(如果已提供)。是否抛出适当异常的决定应在错误流中通过检查异常来做出。以前,任何异常都会直接抛出,导致 HTTP 500 服务器错误响应状态,但在某些情况下,问题可能是由不正确的请求参数引起的,因此应该抛出带有 4xx 客户端错误状态的 ResponseStatusException。更多信息请参见 ResponseStatusException。发送到此错误通道的 ErrorMessage 包含原始异常作为有效负载以供分析。

URI 模板变量和表达式

通过将 path 属性与 payload-expression 属性和 header 元素结合使用,您可以灵活地映射传入的请求数据。

在以下示例配置中,配置了一个入站通道适配器以接受使用以下 URI 的请求:

/first-name/{firstName}/last-name/{lastName}
none

当你使用 payload-expression 属性时,{firstName} URI 模板变量映射为 Message 负载,而 {lastName} URI 模板变量映射为 lname 消息头,如下例所示:

<int-http:inbound-channel-adapter id="inboundAdapterWithExpressions"
path="/first-name/{firstName}/last-name/{lastName}"
channel="requests"
payload-expression="#pathVariables.firstName">
<int-http:header name="lname" expression="#pathVariables.lastName"/>
</int-http:inbound-channel-adapter>
xml

有关 URI 模板变量的更多信息,请参阅 Spring 参考手册中的 uri 模板模式

自从 Spring Integration 3.0 以来,除了现有的 #pathVariables#requestParams 变量可以在有效负载和标题表达式中使用之外,我们还添加了其他有用的表达式变量:

  • #requestParams:来自 ServletRequest parameterMapMultiValueMap

  • #pathVariables:来自 URI 模板占位符及其值的 Map

  • #matrixVariables:根据 Spring MVC 规范MultiValueMapMap。请注意,#matrixVariables 需要 Spring MVC 3.2 或更高版本。

  • #requestAttributes:与当前请求关联的 org.springframework.web.context.request.RequestAttributes

  • #requestHeaders:来自当前请求的 org.springframework.http.HttpHeaders 对象。

  • #cookies:来自当前请求的 jakarta.servlet.http.Cookie 实例的 MultiValueMap<String, Cookie>

请注意,所有这些值(以及其他值)都可以通过 ThreadLocal org.springframework.web.context.request.RequestAttributes 变量在下游消息流中的表达式内访问,如果该消息流是单线程的并且存在于请求线程内。以下示例配置了一个使用 expression 属性的转换器:

<int-:transformer
expression="T(org.springframework.web.context.request.RequestContextHolder).
requestAttributes.request.queryString"/>
xml

出站

要配置出站网关,您可以使用命名空间支持。以下代码片段显示了出站 HTTP 网关的可用配置选项:

<int-http:outbound-gateway id="example"
request-channel="requests"
url="http://localhost/test"
http-method="POST"
extract-request-payload="false"
expected-response-type="java.lang.String"
charset="UTF-8"
request-factory="requestFactory"
reply-timeout="1234"
reply-channel="replies"/>
xml

最重要的是,注意提供了 'http-method' 和 'expected-response-type' 属性。这两个是配置最频繁的值之一。默认的 http-methodPOST,默认的响应类型是 null。当响应类型为 null 时,回复 Message 的负载包含 ResponseEntity,前提是其 HTTP 状态码表示成功(非成功的状态码会抛出异常)。如果您期望不同的类型,例如 String,请提供完全限定的类名(在前面的例子中为 java.lang.String)。有关空响应体的更多信息,请参阅 HTTP 外发组件中的说明。

important

从 Spring Integration 2.1 开始,HTTP 外发网关的 request-timeout 属性被重命名为 reply-timeout,以更好地反映其意图。

important

自 Spring Integration 2.2 起,默认情况下不再启用通过 HTTP 的 Java 序列化。以前,当将 expected-response-type 属性设置为 Serializable 对象时,Accept 标头未正确设置。自 Spring Integration 2.2 以来,SerializingHttpMessageConverter 已更新为将 Accept 标头设置为 application/x-java-serialized-object

但是,因为这可能会与现有应用程序不兼容,所以决定不再自动将此转换器添加到 HTTP 端点。如果您希望使用 Java 序列化,可以通过使用 message-converters 属性(在使用 XML 配置时)或使用 setMessageConverters() 方法(在 Java 配置中),将 SerializingHttpMessageConverter 添加到相应的端点。或者,您可能希望考虑使用 JSON,只要在类路径上有 Jackson 库,JSON 就会被启用。

从 Spring Integration 2.2 开始,您还可以通过使用 SpEL 和 http-method-expression 属性来动态确定 HTTP 方法。注意,此属性与 http-method 互斥。您也可以使用 expected-response-type-expression 属性而不是 expected-response-type,并提供任何有效的 SpEL 表达式来确定响应的类型。以下配置示例使用了 expected-response-type-expression

<int-http:outbound-gateway id="example"
request-channel="requests"
url="http://localhost/test"
http-method-expression="headers.httpMethod"
extract-request-payload="false"
expected-response-type-expression="payload"
charset="UTF-8"
request-factory="requestFactory"
reply-timeout="1234"
reply-channel="replies"/>
xml

如果您的出站适配器要以单向方式使用,您可以使用 outbound-channel-adapter。这意味着成功的响应将在不向回复通道发送任何消息的情况下执行。在任何非成功响应状态码的情况下,它会抛出异常。配置看起来与网关非常相似,如下例所示:

<int-http:outbound-channel-adapter id="example"
url="http://localhost/example"
http-method="GET"
channel="requests"
charset="UTF-8"
extract-payload="false"
expected-response-type="java.lang.String"
request-factory="someRequestFactory"
order="3"
auto-startup="false"/>
xml
备注

要指定 URL,你可以使用 'url' 属性或 'url-expression' 属性。'url' 属性接受一个简单的字符串(带有 URI 变量的占位符,如下所述)。'url-expression' 是一个 SpEL 表达式,以 Message 作为根对象,这使得动态 URL 成为可能。表达式评估后生成的 URL 仍然可以包含 URI 变量的占位符。

在之前的版本中,一些用户使用占位符将整个 URL 替换为 URI 变量。Spring 3.1 中的变化可能会导致某些转义字符(如 '?')出现问题。因此,我们建议,如果你希望在运行时完全生成 URL,则使用 'url-expression' 属性。

映射 URI 变量

如果您的 URL 包含 URI 变量,可以使用 uri-variable 元素将它们映射。此元素适用于 HTTP 外发网关和 HTTP 外发通道适配器。以下示例将 zipCode URI 变量映射到一个表达式:

<int-http:outbound-gateway id="trafficGateway"
url="https://local.yahooapis.com/trafficData?appid=YdnDemo&amp;zip={zipCode}"
request-channel="trafficChannel"
http-method="GET"
expected-response-type="java.lang.String">
<int-http:uri-variable name="zipCode" expression="payload.getZip()"/>
</int-http:outbound-gateway>
xml

uri-variable 元素定义了两个属性:nameexpressionname 属性标识 URI 变量的名称,而 expression 属性用于设置实际值。通过使用 expression 属性,您可以充分利用 Spring 表达式语言 (SpEL) 的全部功能,这使您能够完全动态地访问消息有效负载和消息头。例如,在前面的配置中,getZip() 方法在 Message 的有效负载对象上调用,该方法的结果被用作名为 'zipCode' 的 URI 变量的值。

自从 Spring Integration 3.0,HTTP 外发端点支持 uri-variables-expression 属性,用于指定应评估的 expression,结果是 URL 模板中所有 URI 变量占位符的一个 Map。它提供了一种机制,使你可以根据外发消息使用不同的变量表达式。此属性与 <uri-variable/> 元素互斥。以下示例展示了如何使用 uri-variables-expression 属性:

<int-http:outbound-gateway
url="https://foo.host/{foo}/bars/{bar}"
request-channel="trafficChannel"
http-method="GET"
uri-variables-expression="@uriVariablesBean.populate(payload)"
expected-response-type="java.lang.String"/>
xml

uriVariablesBean 可能定义如下:

public class UriVariablesBean {
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();

public Map<String, ?> populate(Object payload) {
Map<String, Object> variables = new HashMap<String, Object>();
if (payload instanceOf String.class)) {
variables.put("foo", "foo"));
}
else {
variables.put("foo", EXPRESSION_PARSER.parseExpression("headers.bar"));
}
return variables;
}

}
java
备注

uri-variables-expression 必须求值为一个 Map。该 Map 的值必须是 StringExpression 的实例。此 Map 会提供给 ExpressionEvalMap,以便在 outbound Message 的上下文中使用这些表达式进一步解析 URI 变量占位符。

重要提示 uriVariablesExpression 属性提供了一种非常强大的机制来评估 URI 变量。我们预计大多数人会主要使用简单的表达式,如前面的例子。然而,你也可以配置类似 "@uriVariablesBean.populate(#root)" 的内容,在返回的映射中表达式为 variables.put("thing1", EXPRESSION_PARSER.parseExpression(message.getHeaders().get("thing2", String.class)));,其中表达式是动态地在名为 thing2 的消息头中提供的。由于头信息可能来自不可信的来源,HTTP 外发端点在评估这些表达式时使用 SimpleEvaluationContextSimpleEvaluationContext 仅使用 SpEL 功能的一个子集。如果你信任你的消息源,并希望使用受限的 SpEL 构造,请将外发端点的 trustedSpel 属性设置为 true

你可以通过使用自定义的 url-expression 和一些用于构建和编码 URL 参数的工具,来实现需要按消息提供动态 URI 变量的场景。以下示例展示了如何做到这一点:

url-expression="T(org.springframework.web.util.UriComponentsBuilder)
.fromHttpUrl('https://HOST:PORT/PATH')
.queryParams(payload)
.build()
.toUri()"
xml

queryParams() 方法期望一个 MultiValueMap<String, String> 作为参数,因此你可以在执行请求之前,提前构建一组真实的 URL 查询参数。

整个 queryString 也可以作为一个 uri-variable 呈现,如下例所示:

<int-http:outbound-gateway id="proxyGateway" request-channel="testChannel"
url="http://testServer/test?{queryString}">
<int-http:uri-variable name="queryString" expression="'a=A&amp;b=B'"/>
</int-http:outbound-gateway>
xml

在这种情况下,你必须手动提供 URL 编码。例如,你可以使用 org.apache.http.client.utils.URLEncodedUtils#format() 来实现此目的。如前所述,一个手动构建的 MultiValueMap<String, String> 可以通过以下 Java Streams 代码片段转换为 List<NameValuePair> format() 方法的参数:

List<NameValuePair> nameValuePairs =
params.entrySet()
.stream()
.flatMap(e -> e
.getValue()
.stream()
.map(v -> new BasicNameValuePair(e.getKey(), v)))
.collect(Collectors.toList());
java

控制 URI 编码

默认情况下,URL 字符串在发送请求之前会被编码为 URI 对象(参见 UriComponentsBuilder)。在某些非标准 URI 的场景中(例如 RabbitMQ REST API),执行编码是不希望的。<http:outbound-gateway/><http:outbound-channel-adapter/> 提供了一个 encoding-mode 属性。要禁用 URL 编码,将此属性设置为 NONE(默认值为 TEMPLATE_AND_VALUES)。如果您希望部分编码 URL 的某些部分,请在 <uri-variable/> 中使用 expression,如下例所示:

<http:outbound-gateway url="https://somehost/%2f/fooApps?bar={param}" encoding-mode="NONE">
<http:uri-variable name="param"
expression="T(org.apache.commons.httpclient.util.URIUtil)
.encodeWithinQuery('Hello World!')"/>
</http:outbound-gateway>
xml

使用 Java DSL 可以通过 BaseHttpMessageHandlerSpec.encodingMode() 选项来控制此选项。相同的配置适用于 WebFlux 模块Web Services 模块中的类似 outbound 组件。对于更复杂的场景,建议在外部提供的 RestTemplate 上配置一个 UriTemplateHandler;或者在 WebFlux 的情况下 - 使用带有 UriBuilderFactoryWebClient