微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Chronicle Queue 使用 readDocument 读取任何类型的消息

在 Chronicle Queue 中,我写了两种类型的消息。我想使用相同的 tailer 读取此消息,如果可以使用相同的方法,例如使用 tailer.readDocument()。

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

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

队列 消息A 消息A 留言B

在这个例子中,我只需要在消息 A 之后读取消息 B,因为我正在寻找一种方法来读取与消息类型无关的所有条目。

解决方法

最简单的方法是使用 MethodWriter/MethodReader https://github.com/OpenHFT/Chronicle-Queue#high-level-interface

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

  • 仅作为输入的参数
  • 没有预期的返回值或异常。

一个简单的异步接口

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
}
]
,

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。