1、生产者Producer

1)添加依赖

    <dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>0.10.0.0</version>
</dependency>

2)简单推送代码

文档参考:http://kafka.apache.org/0100/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html

同步推送:

 Properties props = new Properties();

 props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "all");
props.put("retries", );
props.put("batch.size", );
props.put("linger.ms", );
props.put("buffer.memory", );
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer<>(props); for(int i = ; i < ; i++)
producer.send(new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i))); producer.close();

异步推送:

public Future<RecordMetadata> send(ProducerRecord<K,V> record,Callback callback)

对比:

If you want to simulate a simple blocking call you can call the get() method immediately:

 byte[] key = "key".getBytes();
byte[] value = "value".getBytes();
ProducerRecord<byte[],byte[]> record = new ProducerRecord<byte[],byte[]>("topic1", key, value)
producer.send(record).get(); Fully non-blocking usage can make use of the Callback parameter to provide a callback that will be invoked when the request is complete. ProducerRecord<byte[],byte[]> record = new ProducerRecord<byte[],byte[]>("topic1", key, value);
producer.send(myRecord,
new Callback() {
public void onCompletion(RecordMetadata metadata, Exception e) {
if(e != null)
e.printStackTrace();
System.out.println("The offset of the record we just sent is: " + metadata.offset());
}
});

2、消费者Consumer

1)添加依赖

    <dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>0.10.0.0</version>
</dependency>

2)简单拉取代码

更多请查看:http://kafka.apache.org/0100/javadoc/index.html?org/apache/kafka/clients/consumer/KafkaConsumer.html

   Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "");
props.put("session.timeout.ms", "");
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<>(props);
consumer.subscribe(Arrays.asList("foo", "bar"));

while (true) {
ConsumerRecords<String, String> records = consumer.poll();
for (ConsumerRecord<String, String> record : records)
System.out.printf("offset = %d, key = %s, value = %s",
          record.offset(), record.key(), record.value());
}

附上以验证通过的producer推送代码:

    public RecordMetadata sendSyncKafkaRequest(String topic, KeyModel keyModel, Object message) {

        logger.info("=== 推送服务开始:sendSyncKafkaRequest start ===");
logger.info("=== topic: " + topic + "===");
logger.info("=== keyModel: " + JSON.toJSONString(keyModel) + "===");
logger.info("=== message: " + JSON.toJSONString(message) + "==="); Properties props = kafkaProducerProperties.getProperties();
KafkaProducer<KeyModel, Object> producer = null;
RecordMetadata recordMetadata = null;
try {
producer = new KafkaProducer<KeyModel, Object>(props);

recordMetadata = producer.send(new ProducerRecord<KeyModel, Object>(topic, keyModel, message)).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} if (recordMetadata != null) {
logger.info("===kafka请求推送成功!Topic:" + recordMetadata.topic() + ";分区:" + recordMetadata.partition() + "===");
} else {
logger.info("=== recordMetadata为 null!本次kafka 写入请求没有完成!===");
} return recordMetadata;
}

005_kafka_Java_API的更多相关文章

  1. [kafka] 005_kafka_Java_API

    1.生产者Producer 1)添加依赖 <dependency> <groupId>org.apache.kafka</groupId> <artifact ...

随机推荐

  1. linux定时任务的设置

    1.  键入 crontab  -e 编辑crontab服务文件 例如 文件内容如下: */2 * * * * /bin/sh /home/admin/jiaoben/buy/deleteFile.s ...

  2. Linux下运行Jmeter测试所遇问题汇总

    一.安装及启动Jmeter  本文原创,专为光荣之路公众号所有,欢迎转发,但转发请务必写出处!  0.下载及安装 下载地址及Linux命令 wget http://mirrors.cnnic.cn/a ...

  3. Hibernate 基础配置及常用功能(二)

    本章主要是描述几种经典映射关系,顺带比较Hibernate4.x和Hibernate5.x之间的区别. 一.建立测试工程目录 有关实体类之间的相互映射关系,Hibernate官方文档其实描述的非常详细 ...

  4. JavaScript confirm 自定义风格及功能实现

    在网上找了一些弹窗插件,例如bootbox, 功能和动画效果都做的很好,但是很难自定义样式. 项目需要,Google相关方法后写了一个Demo, 没有JavaScript confirm切断线程的功能 ...

  5. QT的信号和槽

    QObject::connect(&dummy, SIGNAL(sig()), &thread, SLOT(slot_main())); 这里slot_main()是thread类中的 ...

  6. 20145227&20145201 《信息安全系统设计基础》实验五

    北京电子科技学院(BESTI) 实 验 报 告 课程:信息安全系统设计基础 班级:1452 姓名:(按贡献大小排名)鄢曼君 李子璇 学号:(按贡献大小排名)20145227 20145201 成绩: ...

  7. html table表头斜线

    关于htnl的table的表头斜线,符合表格设计规范,<style> .biaotou { line-height: 5px; text-align: left; } .biaotou { ...

  8. jdbc的实例应用:增删查改实现

    //在jdbc中进行增删查改 //查看所有 public static void findAll() { String url = "jdbc:mysql://localhost:3306/ ...

  9. windows server 2012 r2 远程桌面连接指南

    具体详情请阅览文档  http://pan.baidu.com/s/1jHTCpW6 windows server 2012 r2 远程桌面连接指南 - 作者 rick·bao - 日期 2016-0 ...

  10. 图解说明——究竟什么是Windows句柄

    图解说明——究竟什么是Windows句柄 参考资料:http://blog.csdn.net/newjerryj/article/details/4383701 http://www.cnblogs. ...