在nodejs microservice中设置kafka监听器

时间:2017-08-18 10:48:34

标签: node.js apache-kafka event-driven

我想知道如何继续设置kafka监听器。我应该为每个微服务运行两个单独的进程node server.jsnode kafka-listener.js吗?

我有两个示例代码:

这是运行节点服务器的server.js

    require('dotenv').config() // Accesses the environment variables from .env file at the root of the folder or from the docker environment

var port = process.env.PORT;
const express = require("express"),
    createtables = require("./config/createtables.js"),
    vogels = require('vogels'),
    morgan = require('morgan'),
    logger = require('./config/logger'),
    app = express(),
    bodyParser = require("body-parser");

createtables();


app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

//We are using a different port for testing because we might want to have the development server ON when we run tests
if (process.env.NODE_ENV === "test") {
    port = 3002
}

app.use(morgan('dev', {
    skip: function (req, res) {
        return res.statusCode < 400
    }, stream: process.stderr
}));

app.use(morgan('dev', {
    skip: function (req, res) {
        return res.statusCode >= 400
    }, stream: process.stdout
}));

var routes = require('./api/routes/LRRoutes');
routes(app);


app.listen(port, function(){
    logger.info('Example app listening on port ' + port);
});

module.exports = app; // for testing

这是一个示例kafka监听器(kafka-listener.js):

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

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

consumer.on('error', function (err) {
        console.log('Error:',err);
})

consumer.on('offsetOutOfRange', function (err) {
        console.log('offsetOutOfRange:',err);
})

监听器应该作为单独的进程运行吗?或者还有其他替代方案吗?

如果您有输入,那么一旦收件人收到消息,就会完成路由。请添加它。

0 个答案:

没有答案