将消息从kafka消费者推送到mongodb

时间:2019-04-03 22:55:08

标签: node.js mongodb apache-kafka kafka-consumer-api apache-kafka-connect

在事件

上,我已使用“ kafka-node”创建了kafka使用者。
consumer.on('message' ()=>{
connecting to mongodb and inserting to a collection.
})

mongo.js文件,用于创建与mongo的连接并返回对象

const MongoClient = require('mongodb').MongoClient, assert = require('assert');

const url = 'mongodb://root:****@ds031257.mlab.com:31257/kafka-node';

let _db;

 const connectDB =  (callback) => {
     try {
         MongoClient.connect(url, { useNewUrlParser: true }, (err, database) => {
             console.log('message' + database)
             _db = database.db('kafka-node');
             return callback(err);
         })
     } catch (e) {
         throw e;
     }
 }

 const getDB = () => _db;

 const close = () => _db.close();
 module.exports = { connectDB, getDB, close }

consumer.js用于创建使用者并将消息推送到mongodb

let kafka = require('kafka-node');
let MongoDB = require('./mongo');
let Consumer = kafka.Consumer,
    // The client specifies the ip of the Kafka producer and uses
    // the zookeeper port 2181
    client = new kafka.KafkaClient({ kafkaHost: 'localhost:9093, localhost:9094, localhost:9095' });
// The consumer object specifies the client and topic(s) it subscribes to
consumer = new Consumer(
    client, [{ topic: 'infraTopic', partitions: 3 }], { autoCommit: false });


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

consumer.on('error', function (err) {
    console.log('consumer is in error state');
    console.log(err);
})
client.refreshMetadata(['infraTopic'], (err) => {
    if (err) {
        console.warn('Error refreshing kafka metadata', err);
    }
});
consumer.on('message', function (message) {
    // grab the main content from the Kafka message
    console.log(message);
    MongoDB.connectDB((err) => {
        if (err) throw err
        // Load db & collections
        const db = MongoDB.getDB();
        const collectionKafka = db.collection('sampleCollection');
        try {
            collectionKafka.insertOne(
                {
                    timestamp: message.value,
                    topic: message.topic
                },
                function (err, res) {
                    if (err) {
                        database.close();
                        return console.log(err);
                    }
                    // Success
                }
            )
        } catch (e) {
            throw e
        }
    })
});

这是从kafka使用者向mongodb推送消息的正确方法吗? 通过这种设置,它可以一直工作到所有消息都被写入,并且一旦到达EOL,它就会抛出“无法读取null的'db'属性”

1 个答案:

答案 0 :(得分:1)

  

这是从kafka使用者向mongodb推送消息的正确方法吗?

我猜这是一种的方式,但是我不会称它为 right 的方式:)

更好的方法是使用Kafka Connect。它是Apache Kafka的一部分,旨在完全按照您的意图进行操作-将数据从Kafka流式传输到目标系统(您也可以将其用于将其他系统 to Kafka中的数据流式传输)。

有一个excellent connector for MongoDBcomprehensive documentation,它将完全执行您要尝试执行的操作。

如果您需要在写入数据之前先处理数据,则遵循的模式是使用Kafka Streams,KSQL或您要使用的任何处理工具进行处理-但将其写回Kafka主题 。然后,Kafka Connect会读取该主题并将其流式传输到您的目标。这样,您就可以将责任分离开来,并创建一个更加简单但具有弹性和可扩展性的系统。

相关问题