使用kafkaProducerlnterceptor给消息设置唯一的标识 代码实现
时间: 2024-05-15 11:07:44 浏览: 6
可以使用kafka提供的Header来给消息设置唯一的标识。具体代码实现可以参考以下示例:
```java
public class UniqueIdProducerInterceptor implements ProducerInterceptor<Object, Object> {
private static final String UNIQUE_ID_HEADER = "uniqueId";
@Override
public ProducerRecord<Object, Object> onSend(ProducerRecord<Object, Object> record) {
String uniqueId = UUID.randomUUID().toString();
record.headers().add(new RecordHeader(UNIQUE_ID_HEADER, uniqueId.getBytes()));
return record;
}
@Override
public void onAcknowledgement(RecordMetadata metadata, Exception exception) {
// do nothing
}
@Override
public void close() {
// do nothing
}
@Override
public void configure(Map<String, ?> configs) {
// do nothing
}
}
```
在配置Kafka Producer时,将上述Interceptor加入到interceptor链中即可:
```properties
key.serializer=org.apache.kafka.common.serialization.StringSerializer
value.serializer=org.apache.kafka.common.serialization.StringSerializer
producer.interceptor.classes=com.example.UniqueIdProducerInterceptor
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)