0

似乎手表没有立即动作,以下代码仅在睡眠后输出插入。我怎样才能等到更改流连接?

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());
        }
    }
}
4

1 回答 1

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());
        }
    }
}
于 2019-04-09T19:38:12.160 回答