swift服务器中的同步或异步(完美)

时间:2016-12-26 22:49:47

标签: swift asynchronous server swift3 perfect

我使用Perfect Framework创建了一个Swift 3.0服务器。一切都按预期工作得很好,但我想知道是否有更好的方法来做一些事情。

来自iOS背景我知道总是在不同的线程中调用任何阻塞函数。在服务器中进行开发时,这仍然适用吗?

例如,如果我有一个很长的阻塞任务(比如发出另一个请求或执行大型数据库查询),那么同步调用它会有所不同:

let strings = [ "0.0", "193.16", "5/4", "503.42", "696.58", "25/16", "1082.89", "2/1"]
let values = strings.flatMap(doubleFromDecimalOrFraction)

或者我应该异步这样做吗?

routes.add(method: .get, uri: "/", handler: { request, response in
    longSynchronousTask()
    response.appendBody(string: "Finished")
    response.completed()
})

2 个答案:

答案 0 :(得分:0)

取决于框架。我无法找到有关perfect.org架构的更多信息,但由于它声称在“高性能异步网络引擎”上运行,期望处理请求的线程不应该阻止。

大多数反应式框架(如Node.js,Vert.x)依赖于处理请求的一个或多个事件线程。 如果这些线程阻塞,则无法处理更多请求!

这意味着应该在自己的线程中运行更长时间运行的任务。 有一些框架为它提供了一种机制(比如工作线程)。

然后问题变成:什么是更长时间运行的任务? 如果您的任务以异步方式执行I / O并且只是“等待”I / O,则可以在事件线程上执行此操作。

如果你进行冗长的计算,你可能最好把它放到一个单独的线程中。

答案 1 :(得分:-1)

是的,可以。我使用以下代码测试,没关系。

struct DBOperationQueue {
    static let messageOperationQueue:OperationQueue = {
        let operationQueue = OperationQueue()
        operationQueue.maxConcurrentOperationCount = 5
        return operationQueue
    }()
}

func handler(request: HTTPRequest, response: HTTPResponse) {
    DBOperationQueue.messageOperationQueue.addOperation {

        sleep(10)

        print("sleep complete")

        response.setHeader(.contentType, value: "text/html")
        response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
        response.completed()
    }
}