LrKafkaProducer.<K, V>initProducer

Initializes a KafkaProducer instance for the current Vuser.

public static <K, V> void initProducer(String filePath)

public static <K, V> void initProducer(Properties properties)

public static <K,V> void initProducer(Properties properties, Serializer<K> keySerializer, Serializer<V> valueSerializer)

public static <K, V> void initProducer(Map<String, Object> configs)

public static <K, V> void initProducer(Map<String, Object> configs, Serializer<K> keySerializer, Serializer<V> valueSerializer)


filePathPath of .properties file to load
propertiesProperties object that contains the configuration information for the broker
KeySerializerSerializer object for the key type
ValueSerializerSerializer object for the value type
configsMap of producer configs. Values can be either strings or objects of the appropriate type for the config key, for example: integers for numeric configurations.

Return Values

This function does not return any values.

General information

This function supports both formats that are supported by the original KafkaProducer. For details, see the Apache Kafka documentation. In addition, it supports an option where you can indicate the path of a .properties file to load. Properties and MapEntries that are passed to this function must comply with the format specified by the Kafka documentation.

This method must be called before using any other KafkaProducer function, to ensure that a KafkaProducer instance is created. Otherwise, an error will be printed in the output and the script execution will fail. It is recommended to call this function inside the Vuser init method. For details, see Manually create and edit a Kafka script in the VuGen help center.

Each Vuser can instantiate only one KafkaProducer at a time. Even if this method is called more than once, the Vuser uses the initial KafkaProducer instance and an error is displayed in output file, without terminating the current script execution.

Client ID should not be specified for scripts that will run more than one Vuser.


In the following example, KafkaProducer is initialized in the Vuser init method. The properties passed to the function call are created using the class ProducerConfig and its attributes.

Copy code
public int init() throws Throwable {
         Properties props = new Properties();
         //kafka server
         props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_BROKERS);
         //producer ID
         props.put(ProducerConfig.CLIENT_ID_CONFIG, "ClientID");
         //key serializer
         props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName());
         //value serializer
         props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
         LrKafkaProducer.<Long, String>initProducer(props);
         return 0;