ProducerInterceptorPrefix.java
/**
* 自定义拦截器
*/
public class ProducerInterceptorPrefix implements ProducerInterceptor {
private volatile long sendSuccess = 0;
private volatile long sendFailure = 0;
@Override
public ProducerRecord onSend(ProducerRecord record) {
String value = "prefix-" + record.value();
return new ProducerRecord(record.topic(), record.partition(), record.timestamp(), record.key(), value, record.headers());
}
@Override
public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
if(exception == null){
sendSuccess++;
}else {
sendFailure++;
}
}
@Override
public void close() {
double successRatio = (double) sendSuccess / (sendSuccess + sendFailure);
System.out.println("[INFO]发送成功率=" + String.format("%f", successRatio * 100) + "%");
}
@Override
public void configure(Map<String, ?> configs) {
}
}