【问题标题】:How to verify HTTP/2 connection pooling/reuse in iOS?如何在 iOS 中验证 HTTP/2 连接池/重用?
【发布时间】:2021-09-18 19:12:27
【问题描述】:

从 WWDC 视频中可以清楚地看到,如果我们在服务器上使用 HTTP/2,并且如果我们使用 URLSession,则连接池开箱即用。如何验证这是否有效?

我正在使用URLSessionTaskMetrics 来验证这一点,但是当我看到指标时,它使用的是networkProtocolName 是h2。所以在服务器 HTTP/2 已经启用,但属性isReusedConnectionFALSE

  1. 在 HTTP/2 中,连接被重用以提高性能, 但知道为什么isReusedConnectionfalse
  2. 我需要打开连接池的任何设置吗?还是我 遗漏了什么?
  3. 还有其他方法可以验证 iOS 中的连接池吗?

【问题讨论】:

    标签: ios swift http networking http2


    【解决方案1】:

    isReusedConnection 可以是 truefalse 对于 HTTP/1.1 和 HTTP/2 协议,因为它依赖于 URLSession 的活动连接。

    HTTP/1.1

    URLSession 默认创建一个包含 4 个连接到单个域的连接池,并使用它们发送请求,例如:

    var requestNum = 0
    
    class Metrics : NSObject, URLSessionDataDelegate {
        func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
               for metric in metrics.transactionMetrics {
                    print("\(requestNum). protocol: \(metric.networkProtocolName!), reused: \(metric.isReusedConnection)")
                    requestNum += 1
               }
           }
    }
    
    let metrics = Metrics()
    let session = URLSession(configuration: URLSessionConfiguration.default, delegate: metrics, delegateQueue: nil)
    
    func makeRequests(_ http: String) {
        requestNum = 0
        for i in 0...10 {
            let request = URLRequest(url: URL(string: "https://\(http).akamai.com/demo/tile-\(i).png")!)
            let task = session.dataTask(with: request)
            task.resume()
        }
    }
    
    makeRequests("http1")
    
    Outputs:
    
    0. protocol: http/1.1, reused: false
    1. protocol: http/1.1, reused: true
    2. protocol: http/1.1, reused: true
    3. protocol: http/1.1, reused: false
    4. protocol: http/1.1, reused: false
    5. protocol: http/1.1, reused: false
    6. protocol: http/1.1, reused: true
    7. protocol: http/1.1, reused: true
    8. protocol: http/1.1, reused: true
    9. protocol: http/1.1, reused: true
    10. protocol: http/1.1, reused: true
    

    如您所见,为会话创建了 4 个新连接(重用:false),所有下一个请求稍后重用它们。

    HTTP/2

    URLSession 与 HTTP/1.1 的工作方式相同,但创建到域的单个连接并通过它发送所有请求,例如:

    makeRequests("http2")
    
    Output:
    
    0. protocol: h2, reused: false
    1. protocol: h2, reused: true
    2. protocol: h2, reused: true
    3. protocol: h2, reused: true
    4. protocol: h2, reused: true
    5. protocol: h2, reused: true
    6. protocol: h2, reused: true
    7. protocol: h2, reused: true
    8. protocol: h2, reused: true
    9. protocol: h2, reused: true
    10. protocol: h2, reused: true
    

    只为上面的第一个请求创建新连接,下一个请求稍后再使用它。

    连接寿命

    URLSession 是为典型的客户端应用程序设计的,不会一直保持与服务器的连接。连接在大约 20 秒后处于活动状态,然后会话将其关闭,因此它每次都会为不频繁的请求创建新连接。

    【讨论】:

      猜你喜欢
      • 2019-05-07
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      相关资源
      最近更新 更多