首页 > 解决方案 > Fluent中如何确保所有数据库操作在数据库关闭之前完成?

问题描述

Fluent 操作以异步方式工作,并在操作完成时返回 EventLoopF​​uture。那么,如果代码使用数据库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操作(或任何启动的数据库操作)完成?

标签: swiftvaporvapor-fluent

解决方案


您遇到的问题是您试图使异步操作在同步函数中工作。简而言之 - 你不能。

您要么需要wait()按照注释中显示的方式调用以使函数同步,要么需要使函数异步并返回未来。没有其他方法可以解决它。

但是要回答你的其他问题,如果你想在创建函数之后调用关闭,你需要等待未来返回使用map或者flatMap


推荐阅读