. Httpclientfactory best Practices in Netcore 2.1

Source: Internet
Author: User
httpclientfactory best practices in. NET Core 2.1

A new Httpclientfactory feature appears in ASP. NET Core 2.1.

It helps resolve some common issues that developers may encounter when using httpclient instances to make external Web requests from their applications.

Introduction

in the. Netcore Platform 2.1 New httpclientfactory, Although httpclient this class implements disposable, but uses it when using the declaration using包装块的方式 Usually not the best choice. Processing HttpClient , the underlying socket socket is not released immediately. This HttpClient类 is created specifically for multiple requests to reuse. Requires different base addresses, different HTTP headers, and other scenarios for personalization of requests to manually manage multiple httpclient instances in order to simplify HttpClient instance management ,. NET Core 2.1 Provides a new httpclientfactory-it can be created, cached, and processed HttpClient instance.

What is Httpclientfactory?

in the words of the asp: "An opinionated factory for creating HttpClient instances" (a factory that creates best practices for HttpClient instances), and is an ASP. New features released by Core 2.1. Depending on your previous experience with httpclient, you may have some problems that you might encounter, and sometimes you don't even realize that you have a problem (only in scenarios where the concurrency is not large).

The first problem is that when you create too many httpclients in your code, this in turn produces two problems ...

    1. this is inefficient because each request has its own pool of remote server connections. This means that you need to pay the cost of reconnecting to the remote server for each client you create.
    2. The bigger problem is that if you create a lot of httpclient and use them, you can run out of sockets, and you're basically already using too many sockets too quickly. There is a limit to how many sockets you can open at the same time. when you dispose of a httpclient, the connection it opens remains open for up to 240 seconds in the TIME_WAIT state (if any packets from the remote server still pass).

HttpClient implements IDisposable, which typically causes developers to follow normal patterns when using IDisposable objects and create them in a using block. This ensures that once the object is completed and it has gone out of scope, the object can be destroyed correctly.

Therefore, the best approach is to reuse httpclient instances so that connections can also be reused. HttpClient is a mutable object, but as long as you have no runtime to change it, it is actually thread-safe and can be shared. as a result, a common approach is to register it as a singleton pattern with a DI framework, or to create an object that contains static instances.

However, this can create new problems. using a single httpclient in this way keeps the connection open and does not honor the DNS time-to-live (TTL) setting (in short, the same httpclient instance can have only one request header, and when the requested party changes, because a singleton cannot make a personalized change, Otherwise, cause other requests to fail). Now the connection will never get DNS updates, so the server you are communicating with will never update its address. In some cases, this is entirely possible, in which case you can balance many hosts that may change over time, or may use Blue/green deployment to launch new services. If the server changes, the IP that your connection uses may no longer respond to requests that you make through a single httpclient.

So we need to manually manage the HttpClient instances of each type of server for the construction and initiation of personalized request headers!

Httpclientfactory is designed to help you get started with these issues and provides a new mechanism to create httpclient instances that are properly managed behind the scenes. It will be for us to "do management httpclient", we can focus on the business! Although the above problems were mentioned in reference to HttpClient, in fact the root cause of the problem actually occurred on httpclient, HttpClient used Httpclienthandler. Httpclientfactory manages the lifecycle of handlers so that we have a pool that can be reused, and we can (rotating) rotate them to make DNS obsolete.

the expensive part of using httpclient is actually creating httpclienthandler and connections. bringing these together in this httpclientfacotry means that we can use our resources more efficiently using the sockets on our systems. When you use Httpclientfactory to request httpclient, you actually get a new instance every time, which means that we don't have to worry about changing its state. This httpclient may (or may not) use an existing httpclienthandler in the pool to use an existing open connection.

by default, each newly created Httpclienthandler (derived from Httpmessagehandler) has a life cycle of only 2 minutes. Through services. Addhttpclient() When you create an Httpclientfactory instance, you can control it based on each named client client. Once the life cycle is reached, the handler is not released immediately, but is placed in an out-of-date pool. Any client that relies on Httpclientfactory's handler chain can continue to use it without any problems. There is a background job that checks for expired pools to see if all references to handlers are outside the scope and can be freed at this time. any new requests to the new client after the handler chain expires will get a new handler chain.

This approach works pretty well, but there are other things in the. NET core that might further improve the situation. the . NET Core Team has developed a new managedhandler that can manage DNS more correctly, which in principle can last longer, which means that connections can be shared more effectively. This new handler is also designed to run more consistently across different operating systems. the above handler pool is a reasonable workaround before the work is completed.

How to use Httpclientfactory

We'll start by creating a simple WEBAPI project

Next, we need to go to our Startup.cs file and register a service.

services.AddHttpClient();

Services. Addscoped (typeof (Classinservice)); //Here is nothing to httpclient, please ignore him temporarily

behind the scenes, this will register some of the required services, one of which is the implementation of Ihttpclientfactory. Next, we use him in the business

   Public class Classinservice    {        //<summary>        /// Builder         /// </summary>        /// <param name= "clientfactory" ></param>         Public Classinservice (clientfactory)        {            = clientfactory;        }}
Private voidhttpclientfactorytest () {varClient = _clientfactory.createclient ("This is specifically used to connect the blog Park"); //must and services. The name specified in Addhttpclient () corresponds to the varContent =NewStringcontent ($"sid={sid}&safekey={111}"); Content. Headers.contenttype=NewMediatypeheadervalue ("application/x-www-form-urlencoded"); varResponse = client. Postasync ("Myblogurl", content); }

Here we first add a dependency on the ihttpclientfactory, which will be injected into the classinservice by the DI system. Ihttpclientfactory allows us to request and receive httpclient instances.

we use Httpclientfactory to create the client. behind the scenes, Httpclientfactory will create a new httpclient for us. But wait, it's bad to say that you're using a new httpclient for each request . But the httpclient created here is in the pool he manages, and not every request will be a new socket.

Httpclientfactory collects these Httpclienthandler instances and manages their lifecycles to address some of the previously mentioned issues. Every time we ask for httpclient, we get a new instance that might (or might not) use the existing Httpclienthandler. There is no problem with httpclient itself.

once created, all Httpclienthandler created by this will be kept by default for about 2 minutes. This means that any new requests for the same createclient can share the handler, so you can also share the connection. when httpclient is present, its handlers remain available, and it will share the connection again.

after two minutes, each httpclienthandler is marked as expired. The expiration states only mark them so that they are no longer used when creating any new httpclient instances. However, they are not destroyed immediately, because other httpclient instances may be using them. Httpclientfactory uses a background service to monitor expired handlers, and once they are no longer referenced, they can be freed properly and their connections closed.

Overview

By using httpclientfactory we do not need to consider how to manage the life cycle of httpclient or worry about encountering DNS problems. These are just some of the best use recommendations for httpclient, as well as other advanced uses, such as the combination with Polly.

Reference:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.