From 893e9729ca87a42dd40745e2ac07f720d4376cf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=9B=BD=E4=BC=9F?= <366193849@qq.com> Date: Tue, 20 Sep 2022 15:14:03 +0800 Subject: [PATCH] json aot --- .../PersistenceService.cs | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/FastGithub.DomainResolve/PersistenceService.cs b/FastGithub.DomainResolve/PersistenceService.cs index c4df224..7f844fc 100644 --- a/FastGithub.DomainResolve/PersistenceService.cs +++ b/FastGithub.DomainResolve/PersistenceService.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Net; using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; @@ -14,21 +15,25 @@ namespace FastGithub.DomainResolve /// /// 域名持久化 /// - sealed class PersistenceService + sealed partial class PersistenceService { private static readonly string dataFile = "dnsendpoints.json"; - private static readonly SemaphoreSlim dataLocker = new(1, 1); - private static readonly JsonSerializerOptions jsonOptions = new() - { - WriteIndented = true, - PropertyNameCaseInsensitive = true, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }; + private static readonly SemaphoreSlim dataLocker = new(1, 1); private readonly FastGithubConfig fastGithubConfig; private readonly ILogger logger; + + private record EndPointItem(string Host, int Port); + [JsonSerializable(typeof(EndPointItem[]))] + [JsonSourceGenerationOptions( + WriteIndented = true, + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] + private partial class EndPointItemsContext : JsonSerializerContext + { + } + /// /// 域名持久化 @@ -60,7 +65,7 @@ namespace FastGithub.DomainResolve dataLocker.Wait(); var utf8Json = File.ReadAllBytes(dataFile); - var endPointItems = JsonSerializer.Deserialize(utf8Json, jsonOptions); + var endPointItems = JsonSerializer.Deserialize(utf8Json, EndPointItemsContext.Default.EndPointItemArray); if (endPointItems == null) { return Array.Empty(); @@ -100,7 +105,7 @@ namespace FastGithub.DomainResolve await dataLocker.WaitAsync(CancellationToken.None); var endPointItems = dnsEndPoints.Select(item => new EndPointItem(item.Host, item.Port)).ToArray(); - var utf8Json = JsonSerializer.SerializeToUtf8Bytes(endPointItems, jsonOptions); + var utf8Json = JsonSerializer.SerializeToUtf8Bytes(endPointItems, EndPointItemsContext.Default.EndPointItemArray); await File.WriteAllBytesAsync(dataFile, utf8Json, cancellationToken); } catch (Exception ex)