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

btxsgosb  于 2021-06-06  发布在  Kafka
关注(0)|答案(1)|浏览(820)

我已经在事件中使用“kafka节点”创建了kafka消费者

consumer.on('message' ()=>{
connecting to mongodb and inserting to a collection.
})

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

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创建consumer并将消息推送到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,它就会抛出“cannot read property'db'of null”

idfiyjo8

idfiyjo81#

这是从kafka消费者向mongodb推送消息的正确方法吗?
我想这是一种方式,但我不认为这是正确的方式:)
更好的是使用Kafka连接。它是ApacheKafka的一部分,它的设计目的正是要做您正试图做的事情—将数据从kafka流式传输到目标系统(您也可以使用它将数据从其他系统流式传输到kafka)。
mongodb有一个很好的连接器,它提供了全面的文档,可以完成您想要做的事情。
如果您需要在写入数据之前对其进行处理,那么要遵循的模式是使用kafka streams、ksql或您想要使用的任何处理工具进行处理,但将其写回kafka主题。然后,Kafka连接阅读该主题并将其流式传输到目标。通过这种方式,您可以将责任分离,并构建一个更简单、更具弹性和可扩展性的系统。

相关问题