|
| 1 | +package io.vertx.example.rxjava.database.mongo; |
| 2 | + |
| 3 | +import io.vertx.core.json.JsonObject; |
| 4 | +import io.vertx.example.util.Runner; |
| 5 | +import io.vertx.rxjava.core.AbstractVerticle; |
| 6 | +import io.vertx.rxjava.ext.mongo.MongoClient; |
| 7 | +import rx.Observable; |
| 8 | + |
| 9 | +/* |
| 10 | + * @author <a href="mailto:[email protected]">Julien Viet</a> |
| 11 | + */ |
| 12 | +public class Client extends AbstractVerticle { |
| 13 | + |
| 14 | + private MongoClient mongo; |
| 15 | + |
| 16 | + // Convenience method so you can run it in your IDE |
| 17 | + public static void main(String[] args) { |
| 18 | + Runner.runExample(Client.class); |
| 19 | + } |
| 20 | + |
| 21 | + @Override |
| 22 | + public void start() throws Exception { |
| 23 | + |
| 24 | + JsonObject config = new JsonObject() |
| 25 | + .put("connection_string", "mongodb://localhost:27018") |
| 26 | + .put("db_name", "my_DB"); |
| 27 | + |
| 28 | + // Deploy an embedded mongo database so we can test against that |
| 29 | + vertx.deployVerticle("service:io.vertx.vertx-mongo-embedded-db", db -> { |
| 30 | + if (db.succeeded()) { |
| 31 | + |
| 32 | + // Create the client |
| 33 | + mongo = MongoClient.createShared(vertx, config); |
| 34 | + |
| 35 | + insertAndFind(); |
| 36 | + |
| 37 | + } else { |
| 38 | + System.out.println("Could not start mongo embedded"); |
| 39 | + db.cause().printStackTrace(); |
| 40 | + } |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + private void insertAndFind() { |
| 45 | + // Documents to insert |
| 46 | + Observable<JsonObject> documents = Observable.just( |
| 47 | + new JsonObject().put("username", "temporalfox").put("firstname", "Julien").put("password", "bilto"), |
| 48 | + new JsonObject().put("username", "purplefox").put("firstname", "Tim").put("password", "wibble") |
| 49 | + ); |
| 50 | + |
| 51 | + mongo.rxCreateCollection("users").flatMapObservable(v -> { |
| 52 | + // After collection is created we insert each document |
| 53 | + return documents.flatMap(doc -> mongo.rxInsert("users", doc).toObservable()); |
| 54 | + }).doOnNext(id -> { |
| 55 | + System.out.println("Inserted document " + id); |
| 56 | + }).last().toSingle().flatMap(id -> { |
| 57 | + // Everything has been inserted now we can query mongo |
| 58 | + System.out.println("Insertions done"); |
| 59 | + return mongo.rxFind("users", new JsonObject()); |
| 60 | + }).subscribe(results -> { |
| 61 | + System.out.println("Results " + results); |
| 62 | + }, error -> { |
| 63 | + System.out.println("Err"); |
| 64 | + error.printStackTrace(); |
| 65 | + }); |
| 66 | + } |
| 67 | +} |
0 commit comments