@@ -3,9 +3,9 @@ const { Kafka } = require('@confluentinc/kafka-javascript').KafkaJS;
33
44async function adminFromConsumer ( ) {
55 const kafka = new Kafka ( {
6- kafkaJS : {
7- brokers : [ 'localhost:9092' ] ,
8- }
6+ kafkaJS : {
7+ brokers : [ 'localhost:9092' ] ,
8+ }
99 } ) ;
1010
1111 const consumer = kafka . consumer ( {
@@ -49,18 +49,17 @@ async function adminFromConsumer() {
4949
5050async function adminFromProducer ( ) {
5151 const kafka = new Kafka ( {
52- kafkaJS : {
53- brokers : [ 'localhost:9092' ] ,
54- }
52+ kafkaJS : {
53+ brokers : [ 'localhost:9092' ] ,
54+ }
5555 } ) ;
5656
57- const producer = kafka . producer ( { } ) ;
57+ const producer = kafka . producer ( {
58+ 'metadata.max.age.ms' : 900000 , /* This is set to the default value. */
59+ } ) ;
5860
5961 await producer . connect ( ) ;
6062
61- // The producer can be used as normal
62- await producer . send ( { topic : 'test-topic' , messages : [ { value : 'Hello!' } ] } ) ;
63-
6463 // And the same producer can create an admin client - the producer must have successfully
6564 // been connected before the admin client can be created.
6665 const admin = producer . dependentAdmin ( ) ;
@@ -70,6 +69,23 @@ async function adminFromProducer() {
7069 const listTopicsResult = await admin . listTopics ( ) ;
7170 console . log ( listTopicsResult ) ;
7271
72+ // A common use case for the dependent admin client is to make sure the topic
73+ // is cached before producing to it. This avoids delay in sending the first
74+ // message to any topic. Using the admin client linked to the producer allows
75+ // us to do this, by calling `fetchTopicMetadata` before we produce.
76+ // Here, we cache all possible topics, but it's advisable to only cache the
77+ // topics you are going to produce to (if you know it in advance),
78+ // and avoid calling listTopics().
79+ // Once a topic is cached, it will stay cached for `metadata.max.age.ms`,
80+ // which is 15 minutes by default, after which it will be removed if
81+ // it has not been produced to.
82+ await admin . fetchTopicMetadata ( { topics : listTopicsResult } ) . catch ( e => {
83+ console . error ( 'Error caching topics: ' , e ) ;
84+ } )
85+
86+ // The producer can be used as usual.
87+ await producer . send ( { topic : 'test-topic' , messages : [ { value : 'Hello!' } ] } ) ;
88+
7389 // Disconnect the producer and admin clients in the correct order.
7490 await admin . disconnect ( ) ;
7591 await producer . disconnect ( ) ;
0 commit comments