IntegrationFlow 作為閘道

IntegrationFlow 可以從服務介面開始,該介面提供 GatewayProxyFactoryBean 元件,如下列範例所示

public interface ControlBusGateway {

    void send(String command);
}

...

@Bean
public IntegrationFlow controlBusFlow() {
    return IntegrationFlow.from(ControlBusGateway.class)
            .controlBus()
            .get();
}

介面方法的所有 Proxy 都配備了通道,用於將訊息傳送至 IntegrationFlow 中的下一個整合元件。您可以使用 @MessagingGateway 註解標記服務介面,並使用 @Gateway 註解標記方法。然而,requestChannel 會被忽略,並被 IntegrationFlow 中下一個元件的內部通道覆寫。否則,使用 IntegrationFlow 建立這樣的設定就沒有意義了。

預設情況下,GatewayProxyFactoryBean 會取得傳統的 bean 名稱,例如 [FLOW_BEAN_NAME.gateway]。您可以使用 @MessagingGateway.name() 屬性或多載的 IntegrationFlow.from(Class<?> serviceInterface, Consumer<GatewayProxySpec> endpointConfigurer) 工廠方法來變更該 ID。此外,介面上 @MessagingGateway 註解中的所有屬性都會套用至目標 GatewayProxyFactoryBean。當註解設定不適用時,可以使用 Consumer<GatewayProxySpec> 變體來為目標 Proxy 提供適當的選項。此 DSL 方法從 5.2 版開始提供。

使用 Java 8,您甚至可以使用 java.util.function 介面建立整合閘道,如下列範例所示

@Bean
public IntegrationFlow errorRecovererFlow() {
    return IntegrationFlow.from(Function.class, (gateway) -> gateway.beanName("errorRecovererFunction"))
            .<Object>handle((p, h) -> {
                throw new RuntimeException("intentional");
            }, e -> e.advice(retryAdvice()))
            .get();
}

errorRecovererFlow 可以如下方式使用

@Autowired
@Qualifier("errorRecovererFunction")
private Function<String, String> errorRecovererFlowGateway;