首页 新闻 会员 周边

httpclient导致线程池爆了

0
悬赏园豆:100 [已解决问题] 解决于 2021-02-01 16:48

请问webapi的高并发接口中需要其他服务的数据,处理后并返回,所以使用了httpclient。由于每个请求线程中的HttpClient线程查询.Result都被阻塞了,导致接口请求线程无法被释放,一直增加爆了线程池,这个怎么解决?

cs_net的主页 cs_net | 初学一级 | 园豆:112
提问于:2021-01-19 16:07
< >
分享
最佳答案
0

1、不要直接.Result 使用 await
2、配置线程池
3、不要直接new HttpClient使用IHttpClientFactory

收获园豆:100
通信的搞程序 | 小虾三级 |园豆:1747 | 2021-01-19 16:38

1.使用await接口所在线程还是阻塞中,解决不了问题
2.可以增加线程数,但治标不治本
3.使用了

cs_net | 园豆:112 (初学一级) | 2021-01-19 16:51

@cs_net: 既然是服务方慢导致的话
1、限制请求。
2、是否可以短时间缓存。
3、或者后台定时拉取服务方数据保存下拉,每次请求直接返回

通信的搞程序 | 园豆:1747 (小虾三级) | 2021-01-19 17:17
其他回答(5)
0

用队列可以解决你这个问题

Blog老中医 | 园豆:236 (菜鸟二级) | 2021-01-19 16:54
0

使用优先队列

Rosiness^ | 园豆:47 (初学一级) | 2021-01-19 17:47
0

贴出你的代码

diudiu1 | 园豆:1031 (小虾三级) | 2021-01-20 10:37
0

我都是用HttpWebRequest的先

using System.Net;

代码如下:

public static String sendPost(string url, string body, string contentType = "application/json;charset=UTF-8")
{
String result = null;
try
{
System.Net.ServicePointManager.Expect100Continue = false;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = contentType;
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 600000;//超时600秒(10分钟)
byte[] btBodys = Encoding.UTF8.GetBytes(body);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse != null)
{
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
result = streamReader.ReadToEnd();
httpWebResponse.Close();
streamReader.Close();
}
httpWebRequest.Abort();
httpWebResponse.Close();
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}

为乐而来 | 园豆:1432 (小虾三级) | 2021-01-20 11:40
0

对于高并发场景,必须要保证自己的服务不能挂掉,正常运行。
1、使用信号量Samphore 进行限流
2、像楼上说的,如果可以的话,本地定时存或缓存其他服务的结果。

不安分的黑娃 | 园豆:164 (初学一级) | 2021-01-20 20:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册