本篇博主带来的是Kafka中如何自定义Interceptor及其原理。
Producer拦截器(interceptor)是在Kafka 0.10版本被引入的,主要用于实现clients端的定制化控制逻辑。
对于producer而言,interceptor使得用户在消息发送前以及producer回调逻辑前有机会对消息做一些定制化需求,比如修改消息
等。同时,producer允许用户指定多个interceptor按序作用于同一条消息从而形成一个拦截链(interceptor chain)。Intercetpor的实现接口是org.apache.kafka.clients.producer.ProducerInterceptor
,其定义的方法包括:
获取配置信息和初始化数据时调用。
该方法封装进KafkaProducer.send方法中,即它运行在用户主线程中。Producer确保在消息被序列化以及计算分区前调用该方法。用户可以在该方法中对消息做任何操作,但最好保证不要修改消息所属的topic和分区,否则会影响目标分区的计算
。
该方法会在消息从RecordAccumulator成功发送到Kafka Broker之后,或者在发送过程中失败时调用
。并且通常都是在producer回调逻辑触发之前。onAcknowledgement运行在producer的IO线程中,因此不要在该方法中放入很重的逻辑,否则会拖慢producer的消息发送效率。
关闭interceptor,主要用于执行一些资源清理工作
如前所述,interceptor可能被运行在多个线程中,因此在具体实现时用户需要自行确保线程安全。另外倘若指定了多个interceptor,则producer将按照指定顺序调用它们
,并仅仅是捕获每个interceptor可能抛出的异常记录到错误日志中而非在向上传递。这在使用过程中要特别留意。
实现一个简单的双interceptor组成的拦截链。第一个interceptor会在消息发送前将时间戳信息加到消息value的最前部;第二个interceptor会在消息发送后更新成功发送消息数或失败发送消息数。
package com.buwenbuhuo.kafka.interceptor;
import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import java.util.Map;
/**
* @author 卜温不火
* @create 2020-05-07 17:10
* com.buwenbuhuo.kafka.interceptor - the name of the target package where the new class or interface will be created.
* kafka0506 - the name of the current project.
*/
public class TimeInterceptor implements ProducerInterceptor<String, String> {
@Override
public ProducerRecord<String, String> onSend(ProducerRecord<String, String> record) {
return new ProducerRecord<String, String>(record.topic(), record.partition(), record.timestamp(), record.key(), System.currentTimeMillis() + record.value(), record.headers());
}
@Override
public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
}
@Override
public void close() {
}
@Override
public void configure(Map<String, ?> configs) {
}
}
package com.buwenbuhuo.kafka.interceptor;
import org.apache.kafka.clients.producer.ProducerInterceptor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import java.util.Map;
/**
* @author 卜温不火
* @create 2020-05-07 17:10
* com.buwenbuhuo.kafka.interceptor - the name of the target package where the new class or interface will be created.
* kafka0506 - the name of the current project.
*/
public class CounterInterceptor implements ProducerInterceptor<String, String> {
private long successNum = 0L;
private long errorNum = 0L;
@Override
public ProducerRecord<String, String> onSend(ProducerRecord<String, String> record) {
return record;
}
@Override
public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
if (exception == null) {
successNum++;
} else {
errorNum++;
}
}
@Override
public void close() {
System.out.println("successNum=" + successNum);
System.out.println("errorNum=" + errorNum);
}
@Override
public void configure(Map<String, ?> configs) {
}
}
package com.buwenbuhuo.kafka.interceptor;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
/**
* @author 卜温不火
* @create 2020-05-06 20:21
* com.buwenbuhuo.kafka.producer - the name of the target package where the new class or interface will be created.
* kafka0506 - the name of the current project.
*/
public class CustomProducer {
public static void main(String[] args) {
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop002:9092");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
// 放两个拦截器
ArrayList<String> interceptors = new ArrayList<>();
interceptors.add("com.buwenbuhuo.kafka.interceptor.CounterInterceptor");
interceptors.add("com.buwenbuhuo.kafka.interceptor.TimeInterceptor");
props.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG,interceptors);
//1.创建1个生产者对象
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
//2.调用send方法
for (int i = 0; i < 1000; i++) {
producer.send(new ProducerRecord<String, String>("second", i + "", "message-" + i), (metadata,exception)->{
if(exception==null){
System.out.println("success"+metadata.topic()+"-"+metadata.partition()+"-"+metadata.offset());
}else{
exception.printStackTrace();
}
});
}
//3.关闭生产者
producer.close();
}
}
看 完 就 赞 , 养 成 习 惯 ! ! ! \color{#FF0000}{看完就赞,养成习惯!!!} 看完就赞,养成习惯!!!^ _ ^ ❤️ ❤️ ❤️
码字不易,大家的支持就是我坚持下去的动力。点赞后不要忘了关注我哦!