Producer interceptor (interceptor) was introduced in Kafka 0.10 version, mainly used forRealize the customized control logic on the clients side.
The interface of Intercetpor isorg.apache.kafka.clients.producer.ProducerInterceptor, Its definition methods include:
1.configure(configs)
Called when obtaining configuration information and initializing data.
2.onSend(ProducerRecord)
This method is encapsulated in the KafkaProducer.send method, that is, it runs in the user's main thread.Producer确保在消息被序列化以及计算分区前调用该方法。
The user can do any operation on the message in this method, but it is best to ensure not to modify the topic and partition to which the message belongs, otherwise it will affect the calculation of the target partition
3.onAcknowledgement(RecordMetadata, Exception)
该方法会在消息被应答或消息发送失败时调用, And usually before the producer callback logic is triggered. onAcknowledgement runs in the producer's IO thread, so do not put heavy logic in this method, otherwise it will slow down the producer's message sending efficiency
4.close:
Close the interceptor,主要用于执行一些资源清理工作
As mentioned earlier, the interceptor may be run in multiple threads, so users need to ensure thread safety by themselves during specific implementation. In addition, if multiple interceptors are specified, the producer will call them in the specified order, and only capture the exceptions that may be thrown by each interceptor and record them in the error log instead of passing them up. This should be paid special attention during use.
demand analysis
Implement a simple interception chain composed of dual interceptors.
The first interceptor codes the mobile phone number in the message, such as 13888888888--> 138****8888
The second interceptor counts the number of successfully sent messages or the number of failed messages after the message is sent