业务中对Kafka发送的事件成功与否进行监听并做相应逻辑处理。
首先看Kafka的源码
public interface ProducerListener<K, V> {
/**
* Invoked after the successful send of a message (that is, after it has been acknowledged by the broker).
* @param producerRecord the actual sent record
* @param recordMetadata the result of the successful send operation
*/
default void onSuccess(ProducerRecord<K, V> producerRecord, RecordMetadata recordMetadata) {
onSuccess(producerRecord.topic(), producerRecord.partition(),
producerRecord.key(), producerRecord.value(), recordMetadata);
}
/**
* Invoked after the successful send of a message (that is, after it has been acknowledged by the broker).
* If the method receiving the ProducerRecord is overridden, this method won't be called
* @param topic the destination topic
* @param partition the destination partition (could be null)
* @param key the key of the outbound message
* @param value the payload of the outbound message
* @param recordMetadata the result of the successful send operation
*/
default void onSuccess(String topic, Integer partition, K key, V value, RecordMetadata recordMetadata) {
}
/**
* Invoked after an attempt to send a message has failed.
* @param producerRecord the failed record
* @param exception the exception thrown
*/
default void onError(ProducerRecord<K, V> producerRecord, Exception exception) {
onError(producerRecord.topic(), producerRecord.partition(),
producerRecord.key(), producerRecord.value(), exception);
}
/**
* Invoked after an attempt to send a message has failed.
* If the method receiving the ProducerRecord is overridden, this method won't be called
* @param topic the destination topic
* @param partition the destination partition (could be null)
* @param key the key of the outbound message
* @param value the payload of the outbound message
* @param exception the exception thrown
*/
default void onError(String topic, Integer partition, K key, V value, Exception exception) {
}
/**
* Return true if this listener is interested in success as well as failure.
* @deprecated the result of this method will be ignored.
* @return true to express interest in successful sends.
*/
@Deprecated
default boolean isInterestedInSuccess() {
return false;
}
}
实现上述接口
public class LoggingProducerListener<K,V> implements ProducerListener<K,V>{
protected Logger logger = LogManager.getLogger(getClass());
@Autowired private JdbcTemplate jdbcTemplate;
@Override public void onSuccess(String topic, Integer partition, K key, V value,
RecordMetadata recordMetadata) {
//发送成功
}
@Override
public void onError(String topic, Integer partition, K key, V value, Exception exception) {
//发送失败
}
}
使用
只需要配置JavaConfig Bean即可
@Bean
public ProducerListener producerListener() {
return new LoggingProducerListener();
}