swift - Fluent中如何确保所有数据库操作在数据库关闭之前完成?
问题描述
Fluent 操作以异步方式工作,并在操作完成时返回 EventLoopFuture。那么,如果代码使用数据库shutdown
调用,有没有办法确保在数据库关闭之前完成所有启动的数据库操作?
例如,下面的代码编译良好,但不能确保在数据库中插入建筑对象(Building
是一个 Fluent Model
。)。另一方面,如果我将wait
函数与函数一起使用create
,则操作会同步,但会确保在数据库中创建建筑记录。
func testExample() throws {
let dbs = Databases(threadPool: .init(numberOfThreads: System.coreCount), on: MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount))
try dbs.use(.postgres(url: "<CONNECTIONSTRING>"), as: .psql)
let db = dbs.database(.psql, logger: Logger(label: "Test"), on: dbs.eventLoopGroup.next())!
let building = Building(id: UUID("b0c8f088-df0a-4253-98e4-eb8943c054d4"), buildingName: "Building4")
building.create(on: db)
// This is synchronous and would create a record in the database.
//try building.create(on: db).wait()
dbs.shutdown()
try dbs.threadPool.syncShutdownGracefully()
try dbs.eventLoopGroup.syncShutdownGracefully()
}
有没有办法dbs.shutdown()
等到create
操作(或任何启动的数据库操作)完成?
解决方案
您遇到的问题是您试图使异步操作在同步函数中工作。简而言之 - 你不能。
您要么需要wait()
按照注释中显示的方式调用以使函数同步,要么需要使函数异步并返回未来。没有其他方法可以解决它。
但是要回答你的其他问题,如果你想在创建函数之后调用关闭,你需要等待未来返回使用map
或者flatMap
推荐阅读
- php - 使用特定用户验证私有 vcs
- c# - 跟踪资源在运行时的使用情况以查找缺失的翻译
- module - 如何在 Choregraphe 的应用程序中导入模块(在其中使用相对较大的包)?
- sap - 限制 SAP Hybris Commerce Backoffice 中的枚举值
- methods - F# - 调用方法并分配给构造函数中的属性
- python - 从 url 请求中解压缩 zip 文件
- wpf - 是否可以在 WPF 中使用 GMap.Net Windows Form dll?
- html - 有没有办法使用 CSS 用楔形/三角形装饰线端?
- docker - Docker 提交 - 未保存数据库更改
- matlab - 如何防止带有“assertWarning”的 Matlab 测试将警告文本打印到控制台?