Last active
June 6, 2018 04:32
-
-
Save tilomitra/86ab6a260a638ccc2a44b131b1cb6705 to your computer and use it in GitHub Desktop.
Kafka Producer in NodeJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kafka from "kafka-node" | |
const client = new kafka.Client("http://localhost:2181"); | |
const topics = [ | |
{ | |
topic: "webevents.dev" | |
} | |
]; | |
const options = { | |
autoCommit: true, | |
fetchMaxWaitMs: 1000, | |
fetchMaxBytes: 1024 * 1024, | |
encoding: "buffer" | |
}; | |
const consumer = new kafka.HighLevelConsumer(client, topics, options); | |
consumer.on("message", function(message) { | |
// Read string into a buffer. | |
var buf = new Buffer(message.value, "binary"); | |
var decodedMessage = JSON.parse(buf.toString()); | |
//Events is a Sequelize Model Object. | |
return Events.create({ | |
id: decodedMessage.id, | |
type: decodedMessage.type, | |
userId: decodedMessage.userId, | |
sessionId: decodedMessage.sessionId, | |
data: JSON.stringify(decodedMessage.data), | |
createdAt: new Date() | |
}); | |
}); | |
consumer.on("error", function(err) { | |
console.log("error", err); | |
}); | |
process.on("SIGINT", function() { | |
consumer.close(true, function() { | |
process.exit(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment