更新时间:2022-07-19 GMT+08:00
分享

Old Producer API使用样例

功能介绍

Producer是消息生产者的角色,负责发布消息到Kafka Broker。

下面代码片段在com.huawei.bigdata.kafka.example.Old_Producer类中,作用在于每秒向指定的Topic发送一条消息。(注意:Old Producer API仅支持通过不启用Kerberos认证模式端口访问未设置ACL的Topic,安全接口说明见安全接口说明

样例代码

Old Producer API的run方法中的逻辑

    /*
     * 启动执行producer,每秒发送一条消息。
     */
    public void run()
    {
        LOG.info("Old Producer: start.");
        int messageNo = 1;
        
        while (true)
        {
            String messageStr = new String("Message_" + messageNo);
            
            // 指定消息序号作为key值
            String key = String.valueOf(messageNo);
            producer.send(new KeyedMessage<String, String>(topic, key, messageStr));
            LOG.info("Producer: send " + messageStr + " to " + topic);
            messageNo++;
            
            // 每隔1s,发送1条消息
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
分享:

    相关文档

    相关产品