Search code examples
javaapache-camel

Duplication of Apache Camel messages


How can I create duplicates of some Camel messages by some header condition? For example, I have a message with header key=value1,value2,value3, and I want to have three copies of the same messages with keys key=value1, key=value2, key=value3.

I tried to find some components here https://camel.apache.org/components/3.20.x/, but haven't found any suitable example.


Solution

  • You are using the split component of camel, then it's working.

    from("input:queue")
        .split().method(SplitClass.class, "splitHeaders")
            .to("output:queue");
    
    public class SplitClass{
        public List<String> splitHeaders(@Header("key") String key) {
            List<String> values = Arrays.asList(key.split(","));
            List<String> messages = new ArrayList<>();
            for (String value : values) {
                String message = ExchangeHelper.convertToType(exchange, String.class, exchange.getIn());
                exchange.getIn().setHeader("key", value);
                messages.add(message);
            }
            return messages;
        }
    }