【问题标题】:Chronicle Queue reading any kind of message with readDocumentChronicle Queue 使用 readDocument 读取任何类型的消息
【发布时间】:2021-03-15 03:16:40
【问题描述】:

在编年史队列中,我编写了两种类型的消息。我想使用相同的 tailer 阅读此消息,如果可以使用相同的方法,例如使用 tailer.readDocument()。

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

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

队列 消息A 消息A 消息B

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

【问题讨论】:

    标签: chronicle chronicle-queue chronicle-bytes


    【解决方案1】:

    最简单的方法是使用 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
    }
    ]
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-27
        • 1970-01-01
        • 2020-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多