164

WebApi系列~HttpClient的性能隐患 - 张占岭

 6 years ago
source link: http://www.cnblogs.com/lori/p/7692152.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

WebApi系列~HttpClient的性能隐患

回到目录

最近在进行开发过程中,基于都是接口开发,A站接口访问B接口接口来请求数据,而在这个过程中我们使用的是HttpClient这个框架,当然也是微软自己的框架,性能当前没有问题,但如果你直接使用官方的写法,在高并发时候,会有很大的性能隐患,因为它官方使用的是using的方式,而对于请求量比较大时,这种方法对TCP建立也会过高,即使用完马上释放也会有很多time_out的请求,所有决定把某个用到httpclient的组件做成静态化的!

118538-20171019135023271-435057086.png

118538-20171019135112974-235290420.png

调用,中规中矩的写法

                using (var http = new HttpClient())
                {
                    var json = JsonConvert.SerializeObject(new
                    {
                        target_index = projectName,
                        timestamp = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
                        Level = level.ToString(),
                        Message = message
                    });
                    json = json.Replace("target_index", "@target_index").Replace("timestamp", "@timestamp");
                    var httpContent = new StringContent(json, Encoding.UTF8);
                    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    var result = http.PostAsync(apiLoggerUri, httpContent).Result;
                }

 优化它,做成TCP长链接,所以请求走一个通道

        private static readonly HttpClient _httpClient;
        private ApiLoggerOptions _config;

        static ApiLogger()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = new TimeSpan(0, 0, 10);
            _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
        }

keep-alive关键字可以理解为一个长链接,超时时间也可以在上面进行设置,例如10秒的超时时间,当然并发量太大,这个10秒应该会抛弃很多请求

发送请求的代码没有了using,即这个httpclient不会被手动dispose,而是由系统控制它,当然你的程序重启时,这也就被回收了。

               var json = JsonConvert.SerializeObject(new
                {
                    target_index = projectName,
                    timestamp = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
                    Level = level.ToString(),
                    Message = message
                });
                json = json.Replace("target_index", "@target_index").Replace("timestamp", "@timestamp");
                var httpContent = new StringContent(json, Encoding.UTF8);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                _httpClient.PostAsync(apiLoggerUri, httpContent).Wait();

通过上面的改造,我们我系统性能得到了改善,TCP的连接数也降下来了

118538-20171019140007787-599137492.png

所以对于长链接的多路复用技术,相对于请求过多的情况还是最省资源的!

 回到目录


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK