ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

【转】asp.netcore 高并发下使用HttpClient的方法

2021-05-15 21:33:30  阅读:209  来源: 互联网

标签:asp netcore System jrclientguid client clientFactory action using HttpClient


大家都知道,使用HttpClient,在并发量不大的情况,一般没有任何问题;但是在并发量一上去,如果使用不当,会造成很严重的堵塞的情况。

解决方案如下:

一、可以参考微软官方提供的方法:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2

二、我的解决方案是根据官方提供的方法,选择一种最适合项目的写法进行改造。

1、nuget添加包Microsoft.AspNetCore.Http;

2、startup里ConfigureServices方法添加代码:

 

//添加httpclient方法
services.AddHttpClient("ApiServiceName", c =>
{
c.BaseAddress = new Uri(Configuration["ApiConfig:SystemService"]);//地址从配置文件appsettings.json里取
c.Timeout = TimeSpan.FromSeconds(30);//超时间时间设置为30秒
});
3、在需要用的地方注入进去:(一般在构造函数里)

private ILogger logHelper;
private readonly IHttpContextAccessor httpContextAccessor;
private readonly IHttpClientFactory _clientFactory;
HttpClient client;
public articleService(ILogger<reportService> logger, IHttpContextAccessor _httpContextAccessor, IHttpClientFactory clientFactory)
{
logHelper = logger;
httpContextAccessor = _httpContextAccessor;
_clientFactory = clientFactory;
client = _clientFactory.CreateClient("ApiServiceName");
}
client = _clientFactory.CreateClient("SystemService");  这句话也可以在具体的方法里执行,因为我们的项目全部都是调用接口,所以放构造函数比较省事。

4、添加一个公共方法:

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MuXue.Common
{

/// <summary>
/// 异步调用,并且client是注入方式,传过来
/// 2019-8-21
/// 李朴
/// </summary>
public class MyHttpClientHelper
{

public async Task<T> GetData<T>(HttpClient client, GateWay action, dynamic param)
{
string paramStr = JsonConvert.SerializeObject(param);
string jrclientguid = Guid.NewGuid().ToString("n");
try
{
LogHelper.Info($"MyHttpClientHelper开始,url={client.BaseAddress},action={Utils.GetEnumDescription(action)},postData={paramStr} ,jrclientguid={jrclientguid}---------");

client.DefaultRequestHeaders.Add(CommonConstant.jrclientguid, jrclientguid);

HttpResponseMessage response;
using (HttpContent httpContent = new StringContent(paramStr, Encoding.UTF8))
{
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

response = await client.PostAsync("api/" + Utils.GetEnumDescription(action), httpContent);
}
if (response != null && response.IsSuccessStatusCode)
{
T resp = await response.Content.ReadAsAsync<T>();

return resp;
}
else
{
return default(T);
}
}
catch (Exception ex)
{

throw;
}
finally
{
LogHelper.Info($"MyHttpClientHelper结束,url={client.BaseAddress},action={Utils.GetEnumDescription(action)},postData={paramStr} ,jrclientguid={jrclientguid}---------");
}


}
}
}
这里的参数 GateWay action 也可以换做是接口地址(不包含域名);
5、接着在第3步的那个类里,需要调用接口的地方写方法:
//2、取接口里取
MyHttpClientHelper myHttpClientHelper = new MyHttpClientHelper();
Result<List<Article>> resp=await myHttpClientHelper.GetData<Result<List<Article>>>(client, GateWay.GetNoticeList, null);
这样就完成了。

6、全部用异步方式;
————————————————
版权声明:本文为CSDN博主「沐雪大神」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/puzi0315/article/details/104386547

标签:asp,netcore,System,jrclientguid,client,clientFactory,action,using,HttpClient
来源: https://www.cnblogs.com/Areas/p/14772600.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有