高级特性
除了正常的消息发送和消费,在使用 Kaflca 的过程中难免会遇到一些其他高级应用类的需求
- 消费回溯 可以通过原生 Kaflca 提供的
KaflcaConsumer.seek()
方法来实现 - 延时队列
- 消息轨迹
kafka原生没有提供上面的高级特性,可以通过一定的手段来扩展 Kaflca,
RabbitMQ, 使用到了延时队列、消息轨迹
过期时间(TTL)
可以通过消息timestamp
字段和ConsumerInterceptor
接口的onConsume()
方式来实现消息的TTL功能。
过期消息可以 保存在死信队列中,方便应用通过消费死信队列中消息来进行诊断系统运行状况
可以将消息的TTL的设定值以健值对形式保存在消息的headers字段中,消费者消费到这条消息可以在拦截器根据headers字段设定设定的超时来判断消息是否超时
工具类
public class BytesUtils {
public static byte[] longToBytes(long res){
byte[] buffer = new byte[8];
for (int i = 0; i<8; i++) {
int offset = 64-(i+1)*8;
buffer[i]= (byte) ((res>>offset) & 0xff);
}
return buffer;
}
public static long byteToLong(byte[] b){
long values = 0;
for (int i = 0; i < 8; i++) {
values <<= 8;
values |= (b[i] & 0xff);
}
return values;
}
}
发送端核心代码
KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
String topic = "topic_ttl_test";
ProducerRecord<String,String> record1 = new ProducerRecord<>
("topic_ttl_test",null,System.currentTimeMillis(),
null,"msg_ttl_1",
new RecordHeaders().add(
new RecordHeader("ttl",BytesUtils.longToBytes(20))));
//超时的消息
ProducerRecord<String, String> record2 =
new ProducerRecord<>(topic, null, System.currentTimeMillis() -5*1000, null,
"msg_ ttl_ 2", new RecordHeaders ().
add (new RecordHeader ("ttl", BytesUtils.longToBytes(5))));
ProducerRecord<String, String