kafka笔记(三) kafka API

生产者API测试

public void testProduce(){
        Properties properties = new Properties();
        // broker 列表
        properties.put("metadata.broker.list","s100:9092");
        // 串行化
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put("request.required.acks","1");

        // 创建生产者对象
        Producer<String,String> producer = new KafkaProducer<String,String>(properties);
        // 创建消息
        ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("hadoop-kafka", "1", "hello world");
        // 发送消息
        producer.send(producerRecord);
        // 关闭事务
        producer.close();
    }

消费者API测试

    public void testConsume(){
        Properties props = new Properties();
        props.put("bootstrap.servers", "s100:9092");
        props.put("zookeeper.connect","s100:2181");
        props.put("zookeeper.session.timeout.ms","500");
        props.put("zookeeper.sync.timeout.ms", "200");
        props.put("group.id", "test");
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String,String>(props);
        consumer.subscribe(Arrays.asList("foo", "bar"));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records)
                System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值