写在前面,本篇示例是笔者实践所得,如果不当烦请及时沟通,共同学习。
文章目录
在上篇博文中我们介绍了kafka的框架的基础知识,这篇博文我们从java程序的使用角度去熟悉kafka框架。
1. java客户端访问kafka
1.1 maven依赖
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
注意: kafka-clients的版本主要和自己安装的kafaka版本一致 否则会报错 报错信息如下:
1.2 基础
创建kafka生产者/管理员
@BeforeEach
public void createKafkaProduct(){
Properties prop = new Properties();
//连接指定的kafka集群kafka地址,多个地址用逗号分割
prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "xxx.xx.xx.xx:9092,xxx.xx.xx.xx:9093,xxx.xx.x.xxx:9094");
//消息序列化
prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer .class);
prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
//省略部分kafka 生产者配置
//创建kafka生产者
kafkaProducer = new KafkaProducer(prop);
//创建kafka的管理客户端 用于创建topic
adminClient = KafkaAdminClient.create(prop);
}
创建kafka消费者
@BeforeEach
public void createKafkaConsumer(){
Properties prop = new Properties();
//连接指定的kafka集群kafka地址,多个地址用逗号分割
prop.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "xxx.xx.xx.xx:9092,xxx.xx.xx.xx:9093,xxx.xx.x.xxx:9094");
//消息反序列化
prop.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
prop.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
//从topic最开始的数据进行消费
prop.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
//设置kafka消费组id
prop.put(ConsumerConfig.GROUP_ID_CONFIG,"reader-1");
//省略部分kafka 消费者配置
// 创建kafka消费者
kafkaConsumer = new KafkaConsumer<>(prop);
}
1.3 创建topic
topic是消息存储载体,创建的topic可以制定名称,分区(提供吞吐量)、副本数量(故障转移高可靠性)
//创建分区
public void testTopic(){
//创建一个名为book,分区为2,副本数为3的topic 注意副本数量不能超过brokers否则报错
NewTopic topic = new NewTopic("book",2, (short) 4);
//adminClient在基础中已经进行了实例化 所以此处直接使用对象创建topic
CreateTopicsResult createTopicsResult = adminClient.createTopics(Lists.newArrayList(topic));
try {
createTopicsResult.all().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (createTopicsResult.all().isDone()){
System.out.println("topic创建完毕");
}
}
需要注意副本数量不能超过brokers的数量 否则报如下错误
1.3 生产者发送消息
发送的消息需要选择topic,如果该topic不存在则会自动创建
//生产消息
public void testProduct(){
//设置
String topic = "book";
Integer partition = 0;
Long timeStamp = System.currentTimeMillis();
String key = "余华";
String value = "兄弟";
//创建一个消息
ProducerRecord msg = new ProducerRecord(topic,partition,timeStamp,key,value);
//kafka发送消息
Future sendFturue = kafkaProducer.send(msg);
//获取异步结果
Object result = null;
try {
result = sendFturue.get