编写对文件执行 CRUD 操作的 Verticle

Writing Verticles that performs CRUD Operations on a file

我是 Vert.x 的新手,正在尝试实现一个小型 REST API,它将其数据存储在本地文件系统的 JSON 文件中。

到目前为止,我设法实现了 REST API,因为 Vertx 在这方面有很好的文档记录。

我目前正在寻找的是如何在 Vert.x 中构建数据访问对象的示例。如何实现可以对包含 JSON 的文本文件执行 crud 操作的 Verticle?

你能给我举个例子吗?有什么提示吗?

更新 1:

通过对文件的 CRUD 操作,我想到了以下内容。假设有一个名为 Records 的 REST 资源暴露在路径 /api/v1/user/:userid/records/.

在启动我的 HTTP 服务器的 Verticle 中,我有以下路由。

router.get('/api/user/:userid/records').handler(this.&handleGetRecords)
router.post('/api/user/:userid/records').handler(this.&handleNewRecord)

处理程序方法 handleGetRecordshandleNewRecord 正在使用 Vertx 事件总线发送消息。

request.bodyHandler({ b ->

   def userid = request.getParam('userid')

   logger.info "Reading record for user {}", userid
            vertx.eventBus().send(GET_TIME_ENTRIES.name(), "read time records", [headers: [userId: userid]], { reply ->

   // This handler will be called for every request
   def response = routingContext.response()

   if (reply.succeeded()) {
      response.putHeader("content-type", "text/json")
      // Write to the response and end it
                    response.end(reply.result().body())
   } else {

      logger.warn("Reply failed {}", reply.failed())
      response.statusCode = 500
      response.putHeader("content-type", "text/plain")

      response.end('That did not work out well')
   }
  })
})

然后有另一个verticle消费这些消息GET_TIME_ENTRIESCREATE_TIME_ENTRY。我将此消费者 Verticle 视为 Records 的数据访问对象。此 Verticle 可以读取包含所有用户记录的给定 :userid 的文件。 Verticle能够

这里是读取所有记录的例子

vertx.eventBus().consumer(GET_TIME_ENTRIES.name(), { message ->

    String userId = message.headers().get('userId')
    String absPath = "${this.source}/${userId}.json" as String

    vertx.fileSystem().readFile(absPath, { result ->

        if (result.succeeded()) {
            logger.info("About to read from user file {}", absPath)
            def jsonObject = new JsonObject(result.result().toString())
            message.reply(jsonObject.getJsonArray('records').toString())
        } else {
            logger.warn("User file {} does not exist", absPath)
            message.fail(404, "user ${userId} does not exist")
        }
    })
})

我想要实现的是像上面那样读取文件并将 JSON 反序列化为 POJO(例如 List<Records>)。这似乎比使用 Vertx 的 JsonObject 更方便。我不想操纵 JsonObject 实例。

首先,我认为您使用 EventBus 的方法很好。它可能会慢一点,因为 EventBus 会 serialize/deserialize 你的对象,但它给你一个很好的解耦。

您可以在此处查看另一种方法的示例:
https://github.com/aesteve/vertx-feeds/blob/master/src/main/java/io/vertx/examples/feeds/dao/RedisDAO.java

注意每个方法如何接收处理程序作为其最后一个参数:

public void getMaxDate(String feedHash, Handler<Date> handler) {

更耦合,也更高效。

而更经典更直接的做法,可以看官方的例子:

https://github.com/aokolnychyi/vertx-example/blob/master/src/main/java/com/aokolnychyi/vertx/example/dao/MongoDbTodoDaoImpl.java

你可以看到这里的 DAO 几乎是同步的,但是由于处理程序仍然是异步的,所以无论如何都很好。

我想下面的 link 会对您有所帮助,这是 Vertx crud 操作的一个很好的例子。

Vertx student crud operations using hikari