如何在 Spring Integration java dsl 中使用 uri 变量或参数丰富消息 headers

How to enrich the message headers with uri variables or parameters in Spring Integration java dsl

我正在尝试丰富来自 http 入站网关的 header 消息; 我的 uri 看起来像这样:

requestMapping.setPathPatterns("/context/{fooId}");

但我不知道如何使用 HttpRequestHandlingMessagingGateway 的 setHeaderExpressions 方法来捕获 uri 变量并将其值放入 header。

我对 .enrichHeaders(...) 没有更多的成功,因为这段代码产生了一个异常:

IntegrationFlows.from(requestNotificationChannel())
  .enrichHeaders(h -> h.header("fooId", "#pathVariables.fooId")

从参数中提取 uri-variables and/or 值的好方法是什么?

谢谢!

好吧,您有点误解了 HttpRequestHandlingMessagingGateway 的工作原理,或者我们遗漏了文档中的某些内容。

每个 SpEL 评估都是使用 EvaluationContext 完成的,并且每个组件都是新鲜的。 #pathVariables EvaluationContext 变量只能在请求处理期间从 HttpRequestHandlingMessagingGateway 获得。来自 request 且可用于来自 HttpRequestHandlingMessagingGateway 的消息构建的其他类似变量是:

  • requestAttributes
  • requestParams
  • requestHeaders
  • cookies
  • matrixVariables

我想说的是,它对常规 .enrichHeaders() 不起作用,因为它使用了新的 EvaluationContext,并且所有这些变量都不可用。这就是 HttpRequestHandlingMessagingGateway 提供 setHeaderExpressions 的原因。这是一个如何为您使用它的示例:

private final static SpelExpressionParser PARSER = new SpelExpressionParser();
....
@Bean
public HttpRequestHandlingMessagingGateway httpInboundGateway() {
     ....
     httpInboundGateway.setHeaderExpressions(Collections.singletonMap("fooId", PARSER.parseExpression("#pathVariables.fooId")));
     ....
}

从另一方面来说,如果你的 requestNotificationChannel()DirectChannel,你不会将 HTTP 请求线程留在 .enrichHeaders(),因此你可以这样做:

.enrichHeaders(h -> h.headerFunction("fooId", m ->
                        ((Map<String, String>) RequestContextHolder.currentRequestAttributes()
                                        .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, 0)).get("fooId")))