Spring Integration DSL:使用标头的变压器

ita*_*ind 2 spring-integration

我想使用 Java DSL 进行 Spring Integration,但我不知道如何在转换过程中使用消息头。

我的旧实现有一个像这样的 Transformer:

@Transformer(inputChannel = "inputChannel", outputChannel = "outputChannel")
public EventB transform(
        EventA eventA,
        @Header("a_header") String aHeader,
        @Header("other_header") String otherHeader){
    return new EventB(eventA.getSomeField(), aHeader, otherHeader);
}
Run Code Online (Sandbox Code Playgroud)

现在我有以下 DSL:

@Bean
public IntegrationFlow aFlow(){
    return IntegrationFlows.from(EventASink.INPUT)
        .filter("headers['operation'] == 'OPERATION_A'")
        .transform() //<-- What should I do here?
        .handle(Http.outboundGateway(uri).httpMethod(HttpMethod.POST))
        .get();
}
Run Code Online (Sandbox Code Playgroud)

我查看了transform()方法的实现,发现它可以接收GenericTransformer作为参数,但它似乎只适用于消息有效负载,而且我还需要标头。

我还看到可以使用某种反射,但我不喜欢它,因为它不重构安全。

有什么建议吗?提前致谢。

Art*_*lan 5

由于 DSL 是框架的一部分,并且在您开始使用它之前对其进行编译,因此我们无法推断任何自定义 POJO 方法,因此没有像示例中那样干净的方法来对任何自定义标头进行计数。

重用transform()参数上的这些注释的最接近的方法是使用此.transform()合同:

/**
 * Populate the {@code MessageTransformingHandler} for the {@link MethodInvokingTransformer}
 * to invoke the service method at runtime.
 * @param service the service to use.
 * @param methodName the method to invoke.
 * @return the current {@link IntegrationFlowDefinition}.
 * @see MethodInvokingTransformer
 */
public B transform(Object service, String methodName)
Run Code Online (Sandbox Code Playgroud)

因此,您需要使用该方法声明一个 bean 并在参数中使用它,service同时在参数中提及该方法methodName

访问标头的另一种方法是请求Messagelambda 的整个类型:

/**
 * Populate the {@link MessageTransformingHandler} instance for the provided
 * {@link GenericTransformer} for the specific {@code payloadType} to convert at
 * runtime.
 * Use {@link #transform(Class, GenericTransformer)} if you need access to the
 * entire message.
 * @param payloadType the {@link Class} for expected payload type. It can also be
 * {@code Message.class} if you wish to access the entire message in the transformer.
 * Conversion to this type will be attempted, if necessary.
 * @param genericTransformer the {@link GenericTransformer} to populate.
 * @param <P> the payload type - 'transform from' or {@code Message.class}.
 * @param <T> the target type - 'transform to'.
 * @return the current {@link IntegrationFlowDefinition}.
 * @see MethodInvokingTransformer
 * @see LambdaMessageProcessor
 */
public <P, T> B transform(Class<P> payloadType, GenericTransformer<P, T> genericTransformer) {
Run Code Online (Sandbox Code Playgroud)

在这种情况下,代码可能是这样的:

  .transform(Message.class, m -> m.getHeaders())
Run Code Online (Sandbox Code Playgroud)