Spring Cloud Stream处理器单输入,多行输出

时间:2017-10-25 06:36:56

标签: java spring spring-cloud-stream

我一直试图从kafka流式传输我的json事件,将其展平,然后使用Spring Cloud Stream将其推回到另一个主题。

输入:

{
    "major": "Computer Science",
    "books": [{
        "title": "Learn C",
        "author": "Prof C"
    },
    {
        "title": "Learn Java",
        "author": "Java Expert"
    },{
        "title": "Learn Python",
        "author": "Python Master"
    },]
}

展平流程:

@ServiceActivator(inputChannel = Sink.INPUT, outputChannel = Source.OUTPUT)
public String(String event){
    JSONArray result = new JSONArray();

    JSONObject rawEvent = new JSONObject(event);

    String major = rawEvent.get("major");
    JSONArray books = rawEvent.get("books");

    for (int i = 0; i < books.length; i++){
        JSONObject book = books.get(i);
        book.put("major", major);
        result.put(book)
    }

    return result.toString();
}

只产生:

    [{"major":"Computer Science", "books.title":"Learn C", "books.author":"Prof C"}, 
{"major":"Computer Science", "books.title":"Learn Java", "books.author":"Java Expert"}, 
{"major":"Computer Science", "books.title":"Learn Python", "books.author":"Python Master"}]

我的问题是如何让它变得像这样

{"major":"Computer Science", "books.title":"Learn C", "books.author":"Prof C"}
{"major":"Computer Science", "books.title":"Learn Java", "books.author":"Java Expert"}
{"major":"Computer Science", "books.title":"Learn Python", "books.author":"Python Master"}

所以我可以像我所做的那样推回 mutilple JSONObject而不是单个JSONArray吗?

Afaik,Spring Cloud Stream输出只是一个单一的事件,不适合我上面的情况,为Kafka制作3个事件。

谢谢。

2 个答案:

答案 0 :(得分:1)

确实我误解了。 所以在这种情况下,我建议引入Spring IntegrationEnterprise Integration Patterns。你基本上有一个明确的Splitter案例。有很多例子,但这里有一个快速片段: @Splitter public List<String> split(String input) { // basically split your input into a collection and splitter will send out each element as a separate message } 希望有所帮助

答案 1 :(得分:0)

您制作的是有效的JSON数组。您尝试生成的内容不是有效的JSON。但只要你对它好,你就可以简单地使用StringBuilder并将每个 book.toString()附加到它(而不是JSONArray)。这至少会产生你想要的东西。

此外,这不是一个与Spring Cloud Stream相关的问题,而是一般的Java / JSON问题,所以我想StackOverflow上有更多特定论坛可以为您提供更好的答案。