-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Client.java
62 lines (52 loc) · 1.8 KB
/
Client.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package io.vertx.example.rxjava3.database.mongo;
import io.reactivex.rxjava3.core.Flowable;
import io.vertx.core.Launcher;
import io.vertx.core.json.JsonObject;
import io.vertx.rxjava3.core.AbstractVerticle;
import io.vertx.rxjava3.ext.mongo.MongoClient;
/*
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public class Client extends AbstractVerticle {
private MongoClient mongo;
public static void main(String[] args) {
Launcher.executeCommand("run", Client.class.getName());
}
@Override
public void start() throws Exception {
JsonObject config = new JsonObject()
.put("connection_string", "mongodb://localhost:27018")
.put("db_name", "my_DB");
// Create the client
mongo = MongoClient.createShared(vertx, config);
insertAndFind();
}
private void insertAndFind() {
// Documents to insert
Flowable<JsonObject> documents = Flowable.just(
new JsonObject().put("username", "temporalfox").put("firstname", "Julien").put("password", "bilto"),
new JsonObject().put("username", "purplefox").put("firstname", "Tim").put("password", "wibble")
);
mongo
.rxCreateCollection("users")
.andThen(
// After collection is created we insert each document
documents.flatMap(doc -> mongo.rxInsert("users", doc).toFlowable())
)
.doOnNext(id -> {
System.out.println("Inserted document " + id);
})
.lastElement()
.flatMapSingle(id -> {
// Everything has been inserted now we can query mongo
System.out.println("Insertions done");
return mongo.rxFind("users", new JsonObject());
})
.subscribe(results -> {
System.out.println("Results " + results);
}, error -> {
System.out.println("Err");
error.printStackTrace();
});
}
}