Updated on 2022-09-14 GMT+08:00

Old Producer API Usage Sample

Function Description

Playing as a message producer role, Producer publicize messages on Kafka Broker.

The following code snippet belongs to the run method in the com.huawei.bigdata.kafka.example.Old_Producer class. It is used to send one message to a specific topic per second. (Note: The old Producer APIs support only access to topics without ACL restrictions through ports that have not enabled Kerberos authentication. For details, see Security APIs.)

Sample Code

Logic in the run method of old Producer APIs

    /*
     * Start producer to send a message per second. 
     */
    public void run()
    {
        LOG.info("Old Producer: start.");
        int messageNo = 1;
        
        while (true)
        {
            String messageStr = new String("Message_" + messageNo);
            
            // Specify the message sequence number as the key value.
            String key = String.valueOf(messageNo);
            producer.send(new KeyedMessage<String, String>(topic, key, messageStr));
            LOG.info("Producer: send " + messageStr + " to " + topic);
            messageNo++;
            
            // Send a message every other second.
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }