Search code examples
javaspringspring-bootspring-integrationspring-integration-dsl

How to set several message handlers for channel in spring integration DSL?


I wrote my first spring integration application which reads data from spring RSS and logs it into console:

@Configuration
@EnableIntegration
@IntegrationComponentScan
public class DslConfig {

    @Bean
    public IntegrationFlow feedFlow() throws MalformedURLException {
        return IntegrationFlows.from(inBoundFeedDataAdapter(), configurer -> configurer.poller(Pollers.fixedDelay(1000)))
                .channel(newsChannel())
                .transform(source -> {
                    SyndEntry e = ((SyndEntry) source);
                    return e.getTitle() + " " + e.getLink();
                })
                .handle(messageHandler())
                .get();
    }

    @Bean
    public FeedEntryMessageSourceSpec inBoundFeedDataAdapter() throws MalformedURLException {
        return Feed.inboundAdapter(new URL("https://spring.io/blog.atom"), "some_key");
    }

    @Bean
    public MessageChannel newsChannel() {
        return new DirectChannel();
    }

    @Bean
    public MessageHandler messageHandler() {
        return System.out::println;
    }
}

But I have no idea how can I add one additional handler for writing result into file.

How can I achieve it ?

Additional questions:

What is the meaning of metadata key ?


Solution

  • There is a publishSubscribeChannel() to place in the flow and there you can add subscribe() for several sub-flows. Each of them is going to get the same message to process. If you also add an Executor to the configuration, the process is going to happen in parallel:

    .publishSubscribeChannel(s -> s
                            .applySequence(true)
                            .subscribe(f -> f
                                    .handle((p, h) -> "Hello"))
                            .subscribe(f -> f
                                    .handle((p, h) -> "World!"))
                    );
    

    See more info in Docs: https://docs.spring.io/spring-integration/docs/5.2.0.BUILD-SNAPSHOT/reference/html/dsl.html#java-dsl-subflows