用React阅读Kafka主题 [英] Reading a topic of kafka with react

查看:126
本文介绍了用React阅读Kafka主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,如果这个问题看起来很笼统,对不起,但是我很难解决这个问题.所以我在这里试一下.

I'll start by saying I'm sorry if this question looks generic, but I'm having trouble to solve this. So I'll give it a shot here.

我想用react构建一个kafka主题的使用者,因此每次主题中出现新消息时,它都会渲染出我不知道像网格之类的东西.

I want to build a consumer of a kafka topic with react, so it'll render I don't know something like a grid everytime there's a new message in my topic.

我已经有了使用者的代码:

I already have the code of the consumer:

var kafka = require('kafka-node'),
Consumer = kafka.Consumer,
client = new kafka.Client(),
consumer = new Consumer(
    client,
    [
        { topic: 'logs', partition: 0 }
    ],
    {
        autoCommit: false
    }
),
Producer = kafka.Producer,
client = new kafka.Client(),
producer = new Producer(client);

consumer.on('message', function (message) {
    console.log(message);
});

只要有新消息,就会调用消费者事件开".

anytime there's a new message the consumer's event "on" will be called.

但是我看不到一种将它与react挂钩的方法.

But I can't see a way to hook it up with react.

我想要任何东西,教程,文章或其他任何东西.

I'm up for anything, a tutorial, article, anything at all.

谢谢.

推荐答案

以下是您可以执行的操作的一个示例.本质上,让将要呈现消息信息的组件观察kafka consumer 并将该消息设置为组件状态.然后,该组件将以新消息处于状态的状态进行渲染(任何时候调用setState都会导致该组件进行自我更新).

Here's an example of what you could do. In essence, have the component that will render the message information observe the kafka consumer and set that message in the component's state. The component will then render with the new message in state (any time setState is called, causes the component to update itself).

这假设您要显示消息列表,并且consumer.on回调提供了一条消息,需要将其添加到列表中.

This assumes you want to display a list of messages and the consumer.on callback provides a single message that needs to be added to the list.

var MessageDetails = React.createClass({
    //create a render function for this to render the details about a message
});

var MessageDisplay = React.createClass({
    getInitialState: function() {
        return { messages: [] };
    },

    onComponentDidMount: function() {
        consumer.on('message', function (message) {
            // This updates the state so component will re-render
            var messageList = this.state.messages;
            messageList.push(message);
            this.setState({messages: messageList});
        }.bind(this));
    },

    onComponentWillUnmount: function() {
        // Unsubscribe from the consume here.
    },

    render: function() {
        var messageList = this.state.messages.map(function(message) {
            return (<MessageDetails id={message.id} etc. />);
        });
        return (
          <div className="commentBox">
              {messageList}
          </div>
        );
    }
});

这篇关于用React阅读Kafka主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆