|
如需使用最新稳定版本,请使用 Spring Integration 7.0.4! |
服务激活器和 .handle() 方法
The .handle() EIP 方法的目标是调用任何 MessageHandler 实现或某个 POJO 上的任何方法。
另一种选择是使用 lambda 表达式定义“活动”。
因此,我们引入了一个通用的 GenericHandler<P> 函数式接口。
其 handle 方法需要两个参数:P payload 和 MessageHeaders headers(从 5.1 版本开始)。
有了这个,我们可以按如下方式定义流程:
@Bean
public IntegrationFlow myFlow() {
return IntegrationFlow.from("flow3Input")
.<Integer>handle((p, h) -> p * 2)
.get();
}
上述示例会将接收到的任何整数翻倍。
然而,Spring Integration 的一个主要目标是loose coupling,即通过运行时类型转换将消息负载转换为消息处理器的目标参数。
由于 Java 不支持 lambda 类的泛型类型解析,我们为大多数 EIP 方法和LambdaMessageProcessor引入了一个变通方案,即添加一个额外的payloadType参数。
这样做可以将繁重的转换工作委托给 Spring 的ConversionService,它利用提供的type和请求的消息来匹配目标方法的参数。
以下示例展示了生成的IntegrationFlow可能的外观:
@Bean
public IntegrationFlow integerFlow() {
return IntegrationFlow.from("input")
.<byte[], String>transform(p - > new String(p, "UTF-8"))
.handle(Integer.class, (p, h) -> p * 2)
.get();
}
我们还可以在 ConversionService 中注册一些 BytesToIntegerConverter,以消除额外的 .transform():
@Bean
@IntegrationConverter
public BytesToIntegerConverter bytesToIntegerConverter() {
return new BytesToIntegerConverter();
}
@Bean
public IntegrationFlow integerFlow() {
return IntegrationFlow.from("input")
.handle(Integer.class, (p, h) -> p * 2)
.get();
}