MongoCollection.watch()不能立即观看

时间:2019-04-09 19:36:04

标签: java mongodb changestream

手表似乎不能立即动作,下面的代码仅在睡眠一会后才输出插入内容。我怎样才能等到Change Stream连接好?

public class Mongodb4Test {
    public static void main(String[] args) {
        MongoCollection<Document> col = XXX;
        ChangeStreamIterable<Document> watch = col.watch();

        new Thread(() -> {
            col.insertOne(new Document("key", "val1"));
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            col.insertOne(new Document("key", "val2"));
        }).start();

        for (ChangeStreamDocument<Document> change : watch) {
            if (change.getUpdateDescription() != null)
                System.out.println(change.getUpdateDescription().getUpdatedFields());
            System.out.println(change.getOperationType());
            System.out.println(change.getFullDocument());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

好,发现了问题:我需要先获得迭代器:

public class Mongodb4Test {
    public static void main(String[] args) {
        MongoCollection<Document> col = XXX;
        ChangeStreamIterable<Document> watch = col.watch();
        MongoCursor<ChangeStreamDocument<Document>> iterator = watch.iterator();

        new Thread(() -> {
            col.insertOne(new Document("key", "val1"));
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            col.insertOne(new Document("key", "val2"));
        }).start();

        while (iterator.hasNext()) {
            ChangeStreamDocument<Document> change = iterator.next();
            if (change.getUpdateDescription() != null)
                System.out.println(change.getUpdateDescription().getUpdatedFields());
            System.out.println(change.getOperationType());
            System.out.println(change.getFullDocument());
        }
    }
}