0

我有以下代码可以从 Chronicle 队列中读取(它是用 Kotlin 编写的,但这并不重要):

val queue = ChronicleQueueBuilder.single(path).build()
val tailer = queue.createTailer()

tailer.toEnd()

// // This code is wrong
//    val lastIndex = tailer.index()
//
//    val shift = lastIndex - 10
//    if (shift > 0) {
//        tailer.moveToIndex(lastIndex)
//    }

while (true) {
    val text = await(tailer)

    if (prefix == null) {
        println(text)
    } else {
        if (text.startsWith(prefix)) {
            // Would be nice without additional allocation ...
            println(text.substring(prefix.length + 1))
        }
    }
}

如何修改注释代码以从队列中读取前 10 条记录并继续?

理由:在队列用于显示日志的情况下很有用。您想查看一些以前的日志记录语句并在它们出现时查看新的日志记录语句。

4

2 回答 2

1

我已经为你写了一个测试。请运行它应该工作的相同。

public class ChronicleTest {

private String chroniclePath = "/tmp/chronicle-test";

private int msgCount = 10;

private int i = 0;

    @Test
    public void writeToQ() {
        ChronicleQueue queue = ChronicleQueueBuilder.single(chroniclePath).build();
        ExcerptAppender appender = queue.acquireAppender();
        for (i = 1; i <= msgCount; i++) {
            appender.writeBytes(b -> {
                b.writeInt(i);
            });
        }
        ExcerptTailer tailer = queue.createTailer();
        tailer.toEnd();
        long lastIndex = tailer.index();
        tailer.moveToIndex(lastIndex - 5);

        while (tailer.readBytes(b -> {
            int value = b.readInt();
            System.out.println("Received:" + value);
        }))
            System.out.println("Completed");
    }
}
于 2017-06-28T04:53:20.097 回答
0

除了直接使用索引之外,您还可以使用的方向属性ExcerptTailer

    final SingleChronicleQueue queue = createQueue();

    final int totalRecords = 20;
    final int tailRecords = 10;

    final ExcerptAppender appender = queue.acquireAppender();
    for (int i = 0; i < totalRecords; i++) {
        try(final DocumentContext ctx = appender.writingDocument()) {
            ctx.wire().writeText(Integer.toString(i));
        }
    }

    final ExcerptTailer tailer = queue.createTailer();
    tailer.direction(TailerDirection.BACKWARD).toEnd();

    int rewind = tailRecords;
    final int endCycle = tailer.cycle();
    while(--rewind != 0) {
        try(final DocumentContext ctx = tailer.readingDocument()) {
            if (!ctx.isPresent()) {
                break;
            }

            if (endCycle != tailer.cycle()) {
                System.out.println("Rewound past beginning of cycle");
            }
        }
    }

    tailer.direction(TailerDirection.FORWARD);

    for (int i = 0; i < tailRecords; i++) {
        try(final DocumentContext ctx = tailer.readingDocument()) {
            if (!ctx.isPresent()) {
                break;
            }

            System.out.println(ctx.wire().readText());
        }
    }
于 2017-06-28T07:19:56.650 回答