|
| 1 | +# Basic Producer Example |
| 2 | + |
| 3 | +```javascript |
| 4 | +const { Kafka } = require('../..').KafkaJS |
| 5 | + |
| 6 | +async function producerStart() { |
| 7 | + const producer = new Kafka().producer({ |
| 8 | + 'bootstrap.servers': '<fill>', |
| 9 | + }); |
| 10 | + |
| 11 | + await producer.connect(); |
| 12 | + |
| 13 | + const deliveryReports = await producer.send({ |
| 14 | + topic: 'topic2', |
| 15 | + messages: [ |
| 16 | + { value: 'v222', partition: 0 }, |
| 17 | + { value: 'v11', partition: 0, key: 'x' }, |
| 18 | + ] |
| 19 | + }); |
| 20 | + |
| 21 | + await producer.disconnect(); |
| 22 | +} |
| 23 | + |
| 24 | +producerStart(); |
| 25 | +``` |
| 26 | + |
| 27 | +# Basic Consumer Example |
| 28 | + |
| 29 | +```javascript |
| 30 | +const { Kafka } = require('../..').KafkaJS |
| 31 | + |
| 32 | +async function consumerStart() { |
| 33 | + const consumer = new Kafka().consumer({ |
| 34 | + 'bootstrap.servers': '<fill>', |
| 35 | + 'group.id': 'test', |
| 36 | + 'auto.offset.reset': 'earliest', |
| 37 | + }); |
| 38 | + |
| 39 | + await consumer.connect(); |
| 40 | + |
| 41 | + await consumer.subscribe({ topics: [ "topic" ] }); |
| 42 | + |
| 43 | + consumer.run({ |
| 44 | + eachMessage: async ({ topic, partition, message }) => { |
| 45 | + console.log({ |
| 46 | + topic, |
| 47 | + partition, |
| 48 | + offset: message.offset, |
| 49 | + key: message.key?.toString(), |
| 50 | + value: message.value.toString(), |
| 51 | + }); |
| 52 | + }, |
| 53 | + }); |
| 54 | + |
| 55 | + // When done consuming |
| 56 | + // await consumer.disconnect(); |
| 57 | +} |
| 58 | + |
| 59 | +consumerStart(); |
| 60 | +``` |
| 61 | + |
| 62 | +See the examples in the [examples](examples) directory for more in-depth examples. |
0 commit comments