• .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

  • 相关阅读:
    2.5星|《无条件增长》:管理学常识+一些自己的管理案例
    3.5星|《壹棉壹世界》:棉花引发罪恶的黑奴贸易,影响美国南北战争
    只运行一个exe应用程序的使用案例
    WPF中使用WPFMediaKit视频截图案例
    Meta http-equiv属性详解
    层级数据模板 案例(HierarchicalDataTemplateWindow)
    ApplicationCommands 应用程序常见命令
    mvvm command的使用案例
    MatserDetail自动展开
    键盘焦点和逻辑焦点(Logic Focus与Keyboard Focus )
  • 原文地址:https://www.cnblogs.com/chenyishi/p/9061090.html
Copyright © 2020-2023  润新知