Structured-Streaming 学习四—ProducerTest

这一篇主要是介绍如何写kafka的prodecer代码
照着我人生导师的代码照猫画虎来的~

public class TestProducer extends Thread{
    private final KafkaProducer<String, String> producer;
    private final Boolean isAsync;

    public TestProducer(String topic,Boolean isAsync) {
        String[] str = topic.split(",");
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "host:port");
        properties.put("client.id","testProducer");
        properties.put("key.serializer","org.apache.kafka.common.serialization.IntegerSerializer");
        properties.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");

        producer = new KafkaProducer<String, String>(properties);       
        this.isAsync = isAsync;
    }

    public void run() {
        File file = new File("/path/to/file");  // 要分词的文件所在的位置
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line=1;
            while((tempString = reader.readLine())!= null){
                producer.send(new ProducerRecord<String, String>("topic50",line+"---"+tempString));//topic注意改成你自己的topic
                System.out.println("Success send [" +line+ "] message..");
                line++;
            }
            reader.close();
            System.out.println("Total send [" +line+ "] message..");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(reader !=null)
            {
                try{
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        producer.close();

    }
}

/**
*main函数
**/
public class Main {
    public static void main(String[] args) {
        TestProducer test = new TestProducer("topic50", false);
        test.start();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,409评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,159评论 19 139
  • 星期五的思维导图将过去三周的内容都过了一遍,以前还觉得讲的不是很多,因为后面还有许多内容需要讲,突然发现自己还是有...
    迷茫o阅读 1,189评论 0 0
  • 天边像积了雪 红的蓝的紫的 都有 我想今夜的星星 大概是喝多了春酿的美酒 醉得一塌糊涂 月亮也有了想留住的人 万家...
    铜门深雀阅读 1,792评论 0 0
  • 三生石 刻上我们的名字 希望是抹不去的痕迹
    我爱吃任何鱼阅读 1,445评论 0 2

友情链接更多精彩内容