• Moya:打印请求时各个操作的时间节点


    问题描述:使用Alamofire + Moya请求框架,突然出现第一次请求会非常非常慢的情况,在3s - 10s的时候才会返回数据

    初始以为Moya或者Alamofire出现了问题,于是更新到最新版本,并查看github的issue,并没有其他人出现这种情况,后跟后端进行联调,发现后台安全证书替换为Let's Encrypt,在替换回去后恢复正常

    在测试过程中,一直想要知道Moya通过Alamofire发起请求的过程中每一步的时间是多少,具体是卡在哪个步骤导致的请求过慢,后来发现Alamofire封装的请求包含的有一个属性metrics,这个东西是在Response中进行的返回,可以打印查看具体时间指标。

    然而Moya并没有将这个东西进行返回,所以也就不能在Moya的Response里面进行查看打印,于是寻找Moya调用Alamofire回调的地方,最终在Moya+Alamofire.swift文件里面找到了回调方法,在这里打印,即可获取到请求的过程耗费时间。

    internal func response(callbackQueue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self {
            if let callbackQueue = callbackQueue {
                return response(queue: callbackQueue) { handler  in
                    completionHandler(handler.response, handler.request, handler.data, handler.error)
                }
            } else {
                return response { handler  in
                    print(handler.metrics)
                    completionHandler(handler.response, handler.request, handler.data, handler.error)
                }
            }
        }
    

    在该方法打印metrics即可

    打印如下:

    (Fetch Start) 2020-06-22 07:20:56 +0000
    (Domain Lookup Start) 2020-06-22 07:20:56 +0000
    (Domain Lookup End) 2020-06-22 07:20:56 +0000
    (Connect Start) 2020-06-22 07:20:56 +0000
    (Secure Connection Start) 2020-06-22 07:20:56 +0000
    (Secure Connection End) 2020-06-22 07:20:56 +0000
    (Connect End) 2020-06-22 07:20:56 +0000
    (Request Start) 2020-06-22 07:20:56 +0000
    (Request End) 2020-06-22 07:20:56 +0000
    (Response Start) 2020-06-22 07:20:56 +0000
    (Response End) 2020-06-22 07:20:56 +0000
    (Protocol Name) h2
    (Proxy Connection) NO
    (Reused Connection) NO
    (Fetch Type) Network Load
    (Request Header Bytes) 246
    (Request Body Transfer Bytes) 0
    (Request Body Bytes) 0
    (Response Header Bytes) 157
    (Response Body Transfer Bytes) 560
    (Response Body Bytes) 2433
    (Local Address) ***.**.***.**
    (Local Port) 55732
    (Remote Address) **.***.***.**
    (Remote Port) 443
    (TLS Protocol Version) 0x0303
    (TLS Cipher Suite) 0xC030
    (Cellular) NO
    (Expensive) NO
    (Constrained) NO
    (Multipath) NO
    

    即可看出请求的具体耗时地方在哪

  • 相关阅读:
    Android使用注解代替枚举从而节省系统使用的内存开销
    android9.0系统适配遇到的问题
    android 图片上传图片 报Socket: Broken pipe
    android H5支付 网络环境未能通过安全验证,请稍后再试
    Error:Execution failed for task ':app:processDebugManifest'. Manifest merger failed with multiple errors, see logs
    NightWatch端到端测试
    JavaScript生成斐波那契数列
    Vue Material
    Jasmine
    Postman
  • 原文地址:https://www.cnblogs.com/ChengYing-Freedom/p/13177051.html
Copyright © 2020-2023  润新知