Chronicle队列使用readDocument读取任何类型的消息



在Chronicle队列中,我编写了两种类型的消息。我想使用相同的tailer阅读这些消息,如果可能的话,使用相同的方法,例如使用tailer.readDocument((.

如果可能的话,现在任何人的消息类型都来自不同类型的对象。他们没有关系。

在我实际的读取逻辑中,我需要读取队列的所有条目,并且顺序很重要,例如:

队列消息A消息A消息B

在本例中,我只需要在消息A之后读取消息B,因此我正在寻找一种独立于消息类型读取所有条目的方法。

最简单的方法是使用MethodWriter/MethodReader编写消息https://github.com/OpenHFT/Chronicle-Queue#high-电平接口

首先定义一个异步接口,所有方法都有:

  • 仅作为输入的参数
  • 不需要返回值或异常

一个简单的异步接口

import net.openhft.chronicle.wire.SelfDescribingMarshallable;
interface MessageListener {
void method1(Message1 message);
void method2(Message2 message);
}
static class Message1 extends SelfDescribingMarshallable {
String text;
public Message1(String text) {
this.text = text;
}
}
static class Message2 extends SelfDescribingMarshallable {
long number;
public Message2(long number) {
this.number = number;
}
}

要写入队列,可以调用实现此接口的代理。

SingleChronicleQueue queue1 = ChronicleQueue.singleBuilder(path).build();
MessageListener writer1 = queue1.acquireAppender().methodWriter(MessageListener.class);
// call method on the interface to send messages
writer1.method1(new Message1("hello"));
writer1.method2(new Message2(234));

这些调用产生的消息可以按如下方式转储。

# position: 262568, header: 0
--- !!data #binary
method1: {
text: hello
}
# position: 262597, header: 1
--- !!data #binary
method2: {
number: !int 234
}

要读取消息,您可以提供一个读取器,该读取器使用与您所做的调用相同的调用来调用您的实现。

// a proxy which print each method called on it
MessageListener processor = ObjectUtils.printAll(MessageListener.class)
// a queue reader which turns messages into method calls.
MethodReader reader1 = queue1.createTailer().methodReader(processor);
assertTrue(reader1.readOne());
assertTrue(reader1.readOne());
assertFalse(reader1.readOne());

运行此示例打印:

method1 [!Message1 {
text: hello
}
]
method2 [!Message2 {
number: 234
}
]

Nice@PeterLawrey有一种不同的方法来构建处理器。我的意思是,在你的例子中,你打印了我想要填充两种不同类型对象的对象。直到现在,我还没有找到在同一个监听器中使用这些方法的方法

最新更新