第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Java中使Vertx MongoClient操作同步但不阻塞事件循環(huán)?

如何在Java中使Vertx MongoClient操作同步但不阻塞事件循環(huán)?

桃花長相依 2022-09-01 16:29:13
我正在嘗試使用Vertx MongoClient將新文檔保存到MongoDB,如下所示:MongoDBConnection.mongoClient.save("booking", query, res -> {    if(res.succeeded()) {        documentID = res.result();        System.out.println("MongoDB inserted successfully. + document ID is : " + documentID);    }    else {        System.out.println("MongoDB insertion failed.");    }});if(documentID != null) {    // MongoDB document insertion successful. Reply with a booking ID    String resMsg = "A confirmed booking has been successfully created with booking id as " + documentID +         ". An email has also been triggered to the shared email id " + emailID;    documentID = null;    return new JsonObject().put("fulfillmentText", resMsg);}else {    // return intent response    documentID = null;    return new JsonObject().put("fulfillmentText",         "There is some issues while booking the shipment. Please start afreash.");}上面的代碼成功地將查詢jsonObject寫入MongoDB集合。但是,包含此代碼的函數(shù)始終以 返回 。bookingThere is some issues while booking the shipment. Please start afreash發(fā)生這種情況可能是因為MongoClient處理程序“res”是異步的。但是,我想返回基于成功操作和失敗保存操作的條件響應(yīng)。save()save()如何在Vertx Java中實現(xiàn)它?
查看完整描述

2 回答

?
幕布斯6054654

TA貢獻(xiàn)1876條經(jīng)驗 獲得超7個贊

您的假設(shè)是正確的,您不會等待來自數(shù)據(jù)庫的異步響應(yīng)。你能做的,就是把它包裝在一個像這樣的未來里:


  public Future<JsonObject> save() {

    Future<JsonObject> future = Future.future();

    MongoDBConnection.mongoClient.save("booking", query, res -> {

      if(res.succeeded()) {

        documentID = res.result();

        if(documentID != null) {

          System.out.println("MongoDB inserted successfully. + document ID is : " + documentID);

          String resMsg = "A confirmed booking has been successfully created with booking id as " + documentID +

            ". An email has also been triggered to the shared email id " + emailID;

          future.complete(new JsonObject().put("fulfillmentText", resMsg));

        }else{

          future.complete(new JsonObject().put("fulfillmentText",

            "There is some issues while booking the shipment. Please start afreash."))

        }

      } else {

        System.out.println("MongoDB insertion failed.");

        future.fail(res.cause());

      }

    });

    return future;

  }

然后我假設(shè)你有和端點(diǎn)最終調(diào)用它,例如:


router.route("/book").handler(this::addBooking);

...然后,您可以調(diào)用 save 方法并根據(jù)結(jié)果提供不同的響應(yīng)


public void addBooking(RoutingContext ctx){

    save().setHandler(h -> {

        if(h.succeeded()){

            ctx.response().end(h.result());

        }else{

            ctx.response().setStatusCode(500).end(h.cause());

        }

    })

}


查看完整回答
反對 回復(fù) 2022-09-01
?
梵蒂岡之花

TA貢獻(xiàn)1900條經(jīng)驗 獲得超5個贊

您可以使用 RxJava 2 和反應(yīng)式 Mongo 客戶端 (io.vertx.reactivex.ext.mongo.MongoClient)

下面是一個代碼片段:

部署程序

public class Deployer extends AbstractVerticle {


   private static final Logger logger = getLogger(Deployer.class);


   @Override

   public void start(Future<Void> startFuture) {

      DeploymentOptions options = new DeploymentOptions().setConfig(config());


      JsonObject mongoConfig = new JsonObject()

            .put("connection_string",

                  String.format("mongodb://%s:%s@%s:%d/%s",

                        config().getString("mongodb.username"),

                        config().getString("mongodb.password"),

                        config().getString("mongodb.host"),

                        config().getInteger("mongodb.port"),

                        config().getString("mongodb.database.name")));


      MongoClient client = MongoClient.createShared(vertx, mongoConfig);


      RxHelper.deployVerticle(vertx, new BookingsStorage(client), options)

            .subscribe(e -> {

               logger.info("Successfully Deployed");

               startFuture.complete();

            }, error -> {

               logger.error("Failed to Deployed", error);

               startFuture.fail(error);

            });

   }

}

預(yù)訂存儲


public class BookingsStorage extends AbstractVerticle {


   private MongoClient mongoClient;


   public BookingsStorage(MongoClient mongoClient) {

      this.mongoClient = mongoClient;

   }


   @Override

   public void start() {

      var eventBus = vertx.eventBus();

      eventBus.consumer("GET_ALL_BOOKINGS_ADDRESS", this::getAllBookings);

   }


   private void getAllBookings(Message msg) {

      mongoClient.rxFindWithOptions("GET_ALL_BOOKINGS_COLLECTION", new JsonObject(), sortByDate())

            .subscribe(bookings -> {

                     // do something with bookings

                     msg.reply(bookings);

                  },

                  error -> {

                     fail(msg, error);

                  }

            );

   }


   private void fail(Message msg, Throwable error) {

      msg.fail(500, "An unexpected error occurred: " + error.getMessage());

   }


   private FindOptions sortByDate() {

      return new FindOptions().setSort(new JsonObject().put("date", 1));

   }

}

HttpRouterVerticle


// inside a router handler: 


 vertx.eventBus().rxSend("GET_ALL_BOOKINGS_ADDRESS", new JsonObject())

                 .subscribe(bookings -> {

                     // do something with bookings

                  },

                    e -> {

                      // handle error

                 }); 


查看完整回答
反對 回復(fù) 2022-09-01
  • 2 回答
  • 0 關(guān)注
  • 110 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號