lunes, 7 de marzo de 2022

HttpClient en Asp.Net MVC 5


El inconveniente de utilizar muchas instancias de HttpClient (dentro de un USING) es que finalmente produce errores de tipo "socket exhaustion".

The Problem with using HttpClient as opposed to IHttpClientFactory
The problem associated with using many instance of HttpClient in our app doesn’t come from HttpClient itself. But it comes from HttpMessageHandler and it’s lifetime. When we new up many instances of HttpClient in our app with a using statement, what happen is the HttpClient is disposed of but the socket stays open. This can lead to socket exhaustion problem, you can read more about this issue here.

Using IHttpClientFactory with Asp.Net MVC 5

Para solucionar esto en Asp.Net Core se puede utilizar HttpClientFactory

Pero como HttpClientFactory fue inicialmente desarrollado para .Net Core, su implementación en el .Net Framework se torna difícil y optamos por simplemente utilizar un objeto HttpClient estático, como mensiona aquí: YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE

Pero la implementación con el HttpClient estático (Singleton) tiene problemas en un escenario de balenceo de cargaSingleton HttpClient doesn't respect DNS changes

Singleton HttpClient? Beware of this serious behaviour and how to fix it.


CONCLUSIÓN:

No es recomendable utilizar múltiples instancias de HttpClient en Asp.Net por el problema de socket exhaustion. Lo ideal es implementar IHttpClientFactory, pero como fue desarrollado para .Net Core  su implementación en nuestro sistema ASP.Net MVC 5 no es viable (Dependency Injection).
Una solución de compromiso sería utilizar HttpClient estático pero el sistema no quedaría apto para balanceo de carga.
La solución óptima sería entonces crear un nuevo proyecto .Net Core con microservicios para resolver las llamadas a APIs externas.


No hay comentarios:

Publicar un comentario