【问题标题】:Writing Verticles that performs CRUD Operations on a file编写对文件执行 CRUD 操作的 Verticle
【发布时间】:2017-05-03 14:37:15
【问题描述】:

我是 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。我认为这个消费者垂直是Records 的数据访问对象。这个verticle可以读取给定:userid的包含所有用户记录的文件。垂直可以

  • 添加记录
  • 读取所有记录
  • 读取特定记录
  • 更新记录
  • 删除一条或所有记录

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

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 实例。

【问题讨论】:

  • 文件上的 CRUD 操作是什么意思? Vert.x 有一个用于异步文件操作的 Filesystem API,如果这就是你要找的vertx.io/docs/vertx-core/java/…
  • @tsegismont 感谢您的反馈。我试图更精确。请看我的更新

标签: vert.x


【解决方案1】:

首先,在我看来,您使用 EventBus 的方法很好。它可能会慢一些,因为 EventBus 会序列化/反序列化你的对象,但它给你一个很好的解耦。

您可以在此处查看另一种方法的示例:
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 几乎是同步的,但由于处理程序仍然是异步的,所以没关系。

【讨论】:

  • 我选择了 eventBus 以便能够在集群模式下运行解决方案。但是,对于序列化/反序列化开销,您当然是对的。
【解决方案2】:

我想下面的链接会帮助你,这是 Vertx crud 操作的一个很好的例子。

Vertx student crud operations using hikari

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    相关资源
    最近更新 更多