kafka的Java客户端示例代码(kafka_2.12-0.10.2.1)
使用0.9开始增加的KafkaProducer和KafkaConsumer。
Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>cn.ljh.kafka</groupId>
<artifactId>kafka-helloworld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>kafka-helloworld</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.12</artifactId>
<version>0.10.2.1</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<artifactId>jmxri</artifactId>
<groupId>com.sun.jmx</groupId>
</exclusion>
<exclusion>
<artifactId>jms</artifactId>
<groupId>javax.jms</groupId>
</exclusion>
<exclusion>
<artifactId>jmxtools</artifactId>
<groupId>com.sun.jdmk</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
HelloWorldProducer2.java
package cn.ljh.kafka.kafka_helloworld; import java.util.Date;
import java.util.Properties;
import java.util.Random; import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata; public class HelloWorldProducer2 {
public static void main(String[] args) {
long events = Long.parseLong(args[0]);
Random rnd = new Random(); Properties props = new Properties();
props.put("bootstrap.servers", "192.168.137.176:9092,192.168.137.176:9093,192.168.137.176:9094");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
//配置partitionner选择策略,可选配置
props.put("partitioner.class", "cn.ljh.kafka.kafka_helloworld.SimplePartitioner2"); Producer<String, String> producer = new KafkaProducer<>(props); for (long nEvents = 0; nEvents < events; nEvents++) {
long runtime = new Date().getTime();
String ip = "192.168.2." + rnd.nextInt(255);
String msg = runtime + ",www.example.com," + ip;
ProducerRecord<String, String> data = new ProducerRecord<String, String>("page_visits", ip, msg);
producer.send(data,
new Callback() {
public void onCompletion(RecordMetadata metadata, Exception e) {
if(e != null) {
e.printStackTrace();
} else {
System.out.println("The offset of the record we just sent is: " + metadata.offset());
}
}
});
}
producer.close();
}
}
SimplePartitioner2.java
package cn.ljh.kafka.kafka_helloworld; import java.util.List;
import java.util.Map; import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.PartitionInfo; public class SimplePartitioner2 implements Partitioner { @Override
public void configure(Map<String, ?> configs) {
// TODO Auto-generated method stub } @Override
public int partition(String topic, Object key, byte[] keyBytes,
Object value, byte[] valueBytes, Cluster cluster) {
int partition = 0;
List<PartitionInfo> partitions = cluster.partitionsForTopic(topic);
int numPartitions = partitions.size();
String stringKey = (String) key;
int offset = stringKey.lastIndexOf('.');
if (offset > 0) {
partition = Integer.parseInt( stringKey.substring(offset+1)) % numPartitions;
} return partition;
} @Override
public void close() {
// TODO Auto-generated method stub } }
HelloWorldConsumer2.java
package cn.ljh.kafka.kafka_helloworld; import java.util.Arrays;
import java.util.Properties; import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer; public class HelloWorldConsumer2 { public static void main(String[] args) {
Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.137.176:9092,192.168.137.176:9093,192.168.137.176:9094");
props.put(ConsumerConfig.GROUP_ID_CONFIG ,"test") ;
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); Consumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("page_visits")); 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());
}
}
} }
kafka的Java客户端示例代码(kafka_2.12-0.10.2.1)的更多相关文章
- kafka的Java客户端示例代码(kafka_2.11-0.8.2.2)
1.使用Producer API发送消息到Kafka 从版本0.9开始被KafkaProducer替代. HelloWorldProducer.java package cn.ljh.kafka.ka ...
- 4 kafka集群部署及kafka生产者java客户端编程 + kafka消费者java客户端编程
本博文的主要内容有 kafka的单机模式部署 kafka的分布式模式部署 生产者java客户端编程 消费者java客户端编程 运行kafka ,需要依赖 zookeeper,你可以使用已有的 zo ...
- 正则表达式学习笔记(附:Java版示例代码)
具体学习推荐:正则表达式30分钟入门教程 . 除换行符以外的任意字符\w word,正常字符,可以当做变量名的,字母.数字.下划线.汉字\s space,空白符 ...
- C# WebSocket 服务端示例代码 + HTML5客户端示例代码
WebSocket服务端 C#示例代码 using System; using System.Collections.Generic; using System.Linq; using System. ...
- HDFS的Java客户端操作代码(HDFS的查看、创建)
1.HDFS的put上传文件操作的java代码: package Hdfs; import java.io.FileInputStream; import java.io.FileNotFoundEx ...
- JAVA SSM 示例代码
SSM 即spring+spring mvc+mybatis,开发工具IDEA 1.先看下项目结构如图: 2.主要配置文件 spring-mvc.xml <?xml version=" ...
- kafka生产者java客户端
producer 包含一个用于保存待发送消息的缓冲池,缓冲池中消息是还没来得及传输到kafka集群的消息. 位于底层的kafka I/O线程负责将缓冲池中的消息转换成请求发送到集群.如果在结束prod ...
- java 综合示例代码
package javaenhance.src.cn.itcast.day3; import java.lang.reflect.Constructor; import java.lang.refle ...
- HDFS的java客户端操作代码(Windows上面打jar包,提交至linux运行)
1.通过java.net.URL实现屏幕显示demo1文件的内容 package Hdfs; import java.io.InputStream; import java.net.URL; impo ...
随机推荐
- FLV 封装格式解析
本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10662941.html FLV (Flash Video) 是由 Adobe 公司推出的 ...
- [HEOI2017] 寿司餐厅 + 最大权闭合子图的总结
Description 太长了自己看叭 点这里! Solution 先学一波什么叫最大权闭合子图. 先要明白什么是闭合子图,闭合子图就是给定一个有向图,从中选择一些点组成一个点集V.对于V中任意一个点 ...
- 代码创建 WPF 旋转、翻转动画(汇总)
先建立一个button <Button Width="80" Height="60" Content="旋转" Name=" ...
- JS读取服务器返回的XMl格式字符串
function PostSMS(phoneNumber, sessionID, requestUrl, successAction) { $.ajax( { type: 'POST', url: r ...
- LINQ 【高级查询】
using (Data0216DataContext con = new Data0216DataContext()) { List<Users> ulist = con.Use ...
- JavaSE-基础语法(二)-系统类(java.lang.*)和工具类(java.util.*)
系统类(java.lang.*)和工具类(java.util.*) 一.系统类(java.lang.*) 这个包下包含java语言的核心类,如String.Math.System和Thread类等,使 ...
- java_分数
题目内容: 设计一个表示分数的类Fraction.这个类用两个int类型的变量分别表示分子和分母. 这个类的构造函数是: Fraction(int a, int b) 构造一个a/b的分数. 这个类要 ...
- HTML暗黑料理之a标签执行请求不跳转页面
不是被逼无奈不建议用这HTML暗黑料理. <iframe id="></iframe> <a class="large green button&qu ...
- ubuntu安装docker以及基本用法
ubuntu安装docker以及基本用法 一.安装 安装前先更新apt-get源到最新版本 apt-get update 使用ubuntu自带的docker安装包安装docker apt-get in ...
- 关于wsgi协议的理解
基础概念 首先要了解 WSGI 规范的概念,WSGI(Web Server Gateway Interface)规范描述了web server(Gunicorn,uWSGI等)如何与web appli ...