NSURLSession与Alamofire并发请求


68

我的测试应用程序遇到一些奇怪的行为。我有大约50个同时发送到同一服务器的GET请求。该服务器是资源有限的一小部分硬件上的嵌入式服务器。为了优化每个单个请求的性能,我将Alamofire.Manager如下配置一个实例:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPMaximumConnectionsPerHost = 2
configuration.timeoutIntervalForRequest = 30
let manager = Alamofire.Manager(configuration: configuration)

当我发送请求时,manager.request(...)它们以2对的形式分派(按预期,通过Charles HTTP Proxy检查)。但是,很奇怪的是,由于第一个请求在30秒之内没有完成的所有请求,都会因为同时超时而被取消(即使尚未发送)。这是展示行为的例证:

并发请求图

这是预期的行为吗?如何确保请求在发送之前不会超时?

非常感谢!


也许您实际上想要设置的是`timeoutIntervalForResource , not timeoutIntervalForRequest`?
mattt 2014年

谢谢,但是我尝试了两者,并且同一件事不断发生。
汉尼斯

您的方法在Alamofire 4中不再起作用,请更新
-famfamfam

您使用什么程序制作了这张图?
Nik Kov

@NikKov我使用过photoshop
Hannes

Answers:


125

是的,这是预期的行为。一种解决方案是将请求包装在自定义异步NSOperation子类中,然后使用maxConcurrentOperationCount操作队列的来控制并发请求的数量,而不是HTTPMaximumConnectionsPerHost参数。

原始的AFNetworking很好地完成了将请求包装到操作中的工作,这变得微不足道。但是AFNetworking的NSURLSession实现从来没有这样做,Alamofire也没有。


您可以轻松地将其包装RequestNSOperation子类中。例如:

class NetworkOperation: AsynchronousOperation {

    // define properties to hold everything that you'll supply when you instantiate
    // this object and will be used when the request finally starts
    //
    // in this example, I'll keep track of (a) URL; and (b) closure to call when request is done

    private let urlString: String
    private var networkOperationCompletionHandler: ((_ responseObject: Any?, _ error: Error?) -> Void)?

    // we'll also keep track of the resulting request operation in case we need to cancel it later

    weak var request: Alamofire.Request?

    // define init method that captures all of the properties to be used when issuing the request

    init(urlString: String, networkOperationCompletionHandler: ((_ responseObject: Any?, _ error: Error?) -> Void)? = nil) {
        self.urlString = urlString
        self.networkOperationCompletionHandler = networkOperationCompletionHandler
        super.init()
    }

    // when the operation actually starts, this is the method that will be called

    override func main() {
        request = Alamofire.request(urlString, method: .get, parameters: ["foo" : "bar"])
            .responseJSON { response in
                // do whatever you want here; personally, I'll just all the completion handler that was passed to me in `init`

                self.networkOperationCompletionHandler?(response.result.value, response.result.error)
                self.networkOperationCompletionHandler = nil

                // now that I'm done, complete this operation

                self.completeOperation()
        }
    }

    // we'll also support canceling the request, in case we need it

    override func cancel() {
        request?.cancel()
        super.cancel()
    }
}

然后,当我要发起50个请求时,我将执行以下操作:

let queue = OperationQueue()
queue.maxConcurrentOperationCount = 2

for i in 0 ..< 50 {
    let operation = NetworkOperation(urlString: "http://example.com/request.php?value=\(i)") { responseObject, error in
        guard let responseObject = responseObject else {
            // handle error here

            print("failed: \(error?.localizedDescription ?? "Unknown error")")
            return
        }

        // update UI to reflect the `responseObject` finished successfully

        print("responseObject=\(responseObject)")
    }
    queue.addOperation(operation)
}

这样,这些请求将受到的约束maxConcurrentOperationCount,我们不必担心任何请求都会超时。

这是一个示例AsynchronousOperation基类,它负责与异步/并行NSOperation子类关联的KVN :

//
//  AsynchronousOperation.swift
//
//  Created by Robert Ryan on 9/20/14.
//  Copyright (c) 2014 Robert Ryan. All rights reserved.
//

import Foundation

/// Asynchronous Operation base class
///
/// This class performs all of the necessary KVN of `isFinished` and
/// `isExecuting` for a concurrent `NSOperation` subclass. So, to developer
/// a concurrent NSOperation subclass, you instead subclass this class which:
///
/// - must override `main()` with the tasks that initiate the asynchronous task;
///
/// - must call `completeOperation()` function when the asynchronous task is done;
///
/// - optionally, periodically check `self.cancelled` status, performing any clean-up
///   necessary and then ensuring that `completeOperation()` is called; or
///   override `cancel` method, calling `super.cancel()` and then cleaning-up
///   and ensuring `completeOperation()` is called.

public class AsynchronousOperation : Operation {

    private let stateLock = NSLock()

    private var _executing: Bool = false
    override private(set) public var isExecuting: Bool {
        get {
            return stateLock.withCriticalScope { _executing }
        }
        set {
            willChangeValue(forKey: "isExecuting")
            stateLock.withCriticalScope { _executing = newValue }
            didChangeValue(forKey: "isExecuting")
        }
    }

    private var _finished: Bool = false
    override private(set) public var isFinished: Bool {
        get {
            return stateLock.withCriticalScope { _finished }
        }
        set {
            willChangeValue(forKey: "isFinished")
            stateLock.withCriticalScope { _finished = newValue }
            didChangeValue(forKey: "isFinished")
        }
    }

    /// Complete the operation
    ///
    /// This will result in the appropriate KVN of isFinished and isExecuting

    public func completeOperation() {
        if isExecuting {
            isExecuting = false
        }

        if !isFinished {
            isFinished = true
        }
    }

    override public func start() {
        if isCancelled {
            isFinished = true
            return
        }

        isExecuting = true

        main()
    }

    override public func main() {
        fatalError("subclasses must override `main`")
    }
}

/*
 Abstract:
 An extension to `NSLocking` to simplify executing critical code.

 Adapted from Advanced NSOperations sample code in WWDC 2015 https://developer.apple.com/videos/play/wwdc2015/226/
 Adapted from https://developer.apple.com/sample-code/wwdc/2015/downloads/Advanced-NSOperations.zip
 */

import Foundation

extension NSLocking {

    /// Perform closure within lock.
    ///
    /// An extension to `NSLocking` to simplify executing critical code.
    ///
    /// - parameter block: The closure to be performed.

    func withCriticalScope<T>(block: () throws -> T) rethrows -> T {
        lock()
        defer { unlock() }
        return try block()
    }
}

有此模式的其它可能的变化,只是保证你(一)收益trueasynchronous; (b)按照《并发编程指南:操作队列》中的“配置并发执行操作”部分所述,发布必要的KVNisFinishedisExecutingKVN 。


1
哇,非常感谢Rob,这样的回答很少发生!奇迹般有效。
汉尼斯

1
所有有关Stack Overflow的用户贡献均由cc by-sa 3.0贡献,且需要注明出处。请参阅此页脚底部的链接。归根结底,作者保留Stack Overflow贡献的版权,但我们还授予永久许可,以将这些特定贡献用于任何目的(包括商业用途),唯一的要求是(a)必须注明出处,并且(b)你会分享。简而言之,是的,它是免费使用的。
罗布

1
@JAHelia-不,我不这样做,因为我在执行AsynchronousOperation闭包nil后将其设置为,从而解决了任何强大的参考周期。
罗布

1
@famfamfam-在此异步操作模式中,您将创建新的操作,该操作将在完成此操作后执行所需的操作,并使该操作取决于单个网络请求的所有单个操作。
罗布

1
@famfamfam“我看到maxConcurrentOperationCount = 2您设置了,但是您确实调用了50次请求……”重点在于:OP希望将50个请求排队,但绝不能同时运行两个以上的请求。在maxConcurrentOperationCount简单的使然多少能在任何给定时间运行。(您不希望同时运行太多,因为(a)URLSession无论如何一次只能运行这么多,所以您冒着使后者请求超时的风险;并且(b)涉及内存。)上面的方法实现了可控制的并发度在排队许多请求时。
罗布
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.