zoukankan      html  css  js  c++  java
  • .net core Task.Result Wait等造成502

    这两天公众号项目上线,刚开始项目运行没什么问题,但几天之后,访问量激增,服务器崩溃了,每次请求都返回502,一脸懵逼,无从下手,赶紧开日志里的BUG,拿出来一个个改,BUG都改完之后,没有明显的效果,赶紧网上找资料,找了很多找到了这个罪魁祸首,就是Task.Result,原因如下。

    IIS连接池连接数有限,高并发的情况下多余的请求会处于排队状态,特别是Task.Result会阻塞请求线程,造成了IIS线程池的资源浪费,解决方案,使用异步接口async/await,这样会很快的释放请求线程,节约资源。

    例如:

            [HttpGet, HttpAuth(false)]
            public async Task<IActionResult> GetWeChatInfo(string code)
            {
    
                #region 获取openid
                string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx3e&secret=7c61&code=" + code + "&grant_type=authorization_code";
                string result =await HttpUtil.GetData(url);
                var openInfo = JsonConvert.DeserializeAnonymousType(result, new { access_token = "", refresh_token = "", expires_in = 0, openid = "", scope = "" });
    
                string urlStr2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + openInfo.access_token + "&openid=" + openInfo.openid + "&lang=zh_CN";
                string result2 = await HttpUtil.GetData(urlStr2);
                var userinfo = JsonConvert.DeserializeAnonymousType(result2, new { openid = "", nickname = "", sex = 1, language = "", city = "", province = "", country = "", headimgurl = "", privilege = new List<dynamic>() });
                #endregion
    
                #region 根据openid获取是否关注公众号
                string urlA = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx3&secret=7c6";
                string resultA = await HttpUtil.GetData(urlA);
                var openInfoA = JsonConvert.DeserializeAnonymousType(resultA, new { access_token = "" });
    
                string urlStrB = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + openInfoA.access_token + "&openid=" + userinfo.openid + "&lang=zh_CN";
                string resultC = await HttpUtil.GetData(urlStrB);
                #endregion
    
                var userInfoJson = JObject.Parse(resultC);
                return Success(userInfoJson);
    
            }

    参考链接:

    https://q.cnblogs.com/q/106342/

    https://www.cnblogs.com/farb/p/5014773.html

    https://www.cnblogs.com/vipyoumay/p/5663950.html

  • 相关阅读:
    iOS 的 Block 的使用
    iOS 的Could not find Developer Disk Image错误
    iOS 面试
    iOS 开发工具——统计Crash的工具Crashlytics
    iOS 的 Foundation 框架
    iOS 页面之间的传值总结
    iOS 常用四种数据存储方式
    iOS 的 Delegate Notification KVO
    iOS 的 Delegate 设计模式 及 自定义代理
    iOS 的 NSNumber(对基本数据类型) & NSValue(对结构体) 的装箱
  • 原文地址:https://www.cnblogs.com/chenyishi/p/9061090.html
Copyright © 2011-2022 走看看