Skip to content

Commit

Permalink
Added HttpClientFactory to reuse HttpClient
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom-Sloboda committed Mar 15, 2024
1 parent 3a0dbc9 commit 62bd1f4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/GeoblockingMiddleware/Common.fs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ open System
open System.Net.Http
open Newtonsoft.Json
open System.Collections.Concurrent
open Microsoft.Extensions.DependencyInjection

type IpApiModel = { status: string; countryCode: string }

Expand Down Expand Up @@ -55,13 +56,16 @@ module Common =
TimeoutMs = 5000
Service = Ip_Api }

let services = new ServiceCollection()
let httpClientFactory = services.AddHttpClient().BuildServiceProvider().GetService<IHttpClientFactory>()

/// Keep in memory a list of the latest ip addresses with their blocking status.
/// This is public so it can be cleaned with scheduled task outside of this library.
let lastIpAddressesCache = ConcurrentDictionary<string, GeoblockStatus>()

let serviceCallIpApi (ipAddress: string) timeout =
task {
use httpClient = new HttpClient(Timeout = TimeSpan.FromMilliseconds timeout)
let httpClient = httpClientFactory.CreateClient(Timeout = TimeSpan.FromMilliseconds timeout)

let! json = httpClient.GetStringAsync($"http://ip-api.com/json/{ipAddress}?fields=status,countryCode")

Expand All @@ -76,7 +80,7 @@ module Common =

let serviceCallIpInfo (token: string) (ipAddress: string) timeout =
task {
use httpClient = new HttpClient(Timeout = TimeSpan.FromMilliseconds timeout)
let httpClient = httpClientFactory.CreateClient(Timeout = TimeSpan.FromMilliseconds timeout)

httpClient.DefaultRequestHeaders.Accept.Add(
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
Expand Down
4 changes: 4 additions & 0 deletions src/GeoblockingMiddleware/GeoblockingMiddleware.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,9 @@
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
</ItemGroup>

</Project>

0 comments on commit 62bd1f4

Please sign in to comment.