Skip to content

Commit

Permalink
feat: 性能优化 (#469)
Browse files Browse the repository at this point in the history
  • Loading branch information
joesdu authored Jun 20, 2024
2 parents 03cdf9e + 1222207 commit e9551da
Show file tree
Hide file tree
Showing 28 changed files with 226 additions and 216 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ CONNECTIONSTRINGS_MONGO=mongodb://joe:[email protected]:27017/?authSo
CONNECTIONSTRINGS_RABBIT=amqp://admin:a123456@rabbit:5672/%2f

# Garnet 链接字符串
GARNET_URI=garnet:3278,password=a123456
CONNECTIONSTRINGS_GARNET=garnet:3278,password=a123456
1 change: 1 addition & 0 deletions docker-compose.override.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,6 @@ services:
- DASHBOARD_OTLP_PRIMARYAPIKEY=${DASHBOARD_OTLP_PRIMARYAPIKEY}
- CONNECTIONSTRINGS_MONGO=${CONNECTIONSTRINGS_MONGO}
- CONNECTIONSTRINGS_RABBIT=${CONNECTIONSTRINGS_RABBIT}
- CONNECTIONSTRINGS_GARNET=${CONNECTIONSTRINGS_GARNET}
ports:
- 8848:8080
9 changes: 9 additions & 0 deletions sample/WebApi.Test.Unit/Common/Constant.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace WebApi.Test.Unit.Common;

internal static class Constant
{
/// <summary>
/// InstanceName
/// </summary>
internal const string InstanceName = "EasilyNET";
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Net;

namespace WebApi.Test.Unit;
namespace WebApi.Test.Unit.Common;

/// <summary>
/// 返回对象实体
Expand Down
3 changes: 2 additions & 1 deletion sample/WebApi.Test.Unit/Controllers/MongoTestController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using EasilyNET.WebCore.Swagger.Attributes;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;
using MongoDB.Driver;
using System.ComponentModel;

Expand Down Expand Up @@ -54,7 +55,7 @@ public Task MongoPost()
/// 测试从MongoDB中取出插入的数据,再返回到Swagger查看数据JSON转换是否正常
/// </summary>
/// <returns></returns>
[HttpGet("MongoGet")]
[HttpGet("MongoGet"), OutputCache]
public async Task<IEnumerable<MongoTest>> MongoGet() => await db.Test.Find(bf.Empty).ToListAsync();

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
using WebApi.Test.Unit.Common;

// ReSharper disable UnusedType.Global
// ReSharper disable UnusedMember.Global
Expand Down
25 changes: 3 additions & 22 deletions sample/WebApi.Test.Unit/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
using Serilog.Sinks.OpenTelemetry;
using Serilog.Sinks.SystemConsole.Themes;
using WebApi.Test.Unit;
using WebApi.Test.Unit.Common;

Console.Title = "❤️ EasilyNET";
Console.Title = $"❤️ {Constant.InstanceName}";
AssemblyHelper.AddExcludeLibs("Npgsql.");
var builder = WebApplication.CreateBuilder(args);

Expand Down Expand Up @@ -48,7 +49,7 @@
};
c.ResourceAttributes = new Dictionary<string, object>
{
["service.name"] = hbc.Configuration["OTEL_SERVICE_NAME"] ?? "EasilyNET"
["service.name"] = hbc.Configuration["OTEL_SERVICE_NAME"] ?? Constant.InstanceName
};
});
});
Expand All @@ -58,28 +59,8 @@
builder.Services.AddApplication<AppWebModule>();
var app = builder.Build();
if (app.Environment.IsDevelopment()) app.UseDeveloperExceptionPage();
app.Use(async (c, next) =>
{
c.Response.Headers.AddRange([
new("Strict-Transport-Security", "max-age=63072000; includeSubdomains; preload"),
new("X-Content-Type-Options", "nosniff"),
new("X-XSS-Protection", "1; mode=block"),
new("X-Frame-Options", "sameorigin"),
new("Referrer-Policy", "strict-origin-when-cross-origin"),
new("X-Download-Options", "noopen"),
new("X-Permitted-Cross-Domain-Policies", "none"),
new("Cache-control", "max-age=1, no-cache, no-store, must-revalidate, private")
]);
await next();
});

// 添加自动化注入的一些中间件.
app.InitializeApplication();
// 配置健康检查端点
app.MapHealthChecks("/health");
app.MapHealthChecks("/alive", new()
{
Predicate = r => r.Tags.Contains("live")
});
app.MapControllers();
app.Run();
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
using System.Text.Json.Serialization;
using WebApi.Test.Unit.Common;

// ReSharper disable UnusedType.Local
// ReSharper disable ClassNeverInstantiated.Global
Expand Down
8 changes: 7 additions & 1 deletion sample/WebApi.Test.Unit/ServiceModules/MemoryCacheModule.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using EasilyNET.AutoDependencyInjection.Contexts;
using EasilyNET.AutoDependencyInjection.Modules;
using WebApi.Test.Unit.Common;

namespace WebApi.Test.Unit;

Expand All @@ -9,7 +10,12 @@ internal sealed class MemoryCacheModule : AppModule
/// <inheritdoc />
public override void ConfigureServices(ConfigureServicesContext context)
{
context.Services.AddDistributedMemoryCache();
var config = context.Services.GetConfiguration();
context.Services.AddStackExchangeRedisCache(c =>
{
c.Configuration = config["CONNECTIONSTRINGS_GARNET"];
c.InstanceName = Constant.InstanceName;
});
base.ConfigureServices(context);
}
}
18 changes: 12 additions & 6 deletions sample/WebApi.Test.Unit/ServiceModules/OpenTelemetryModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,7 @@ public override void ConfigureServices(ConfigureServicesContext context)
.WithMetrics(c =>
{
c.AddRuntimeInstrumentation();
c.AddMeter([
"Microsoft.AspNetCore.Hosting",
"Microsoft.AspNetCore.Server.Kestrel",
"System.Net.Http",
"WebApi.Test.Unit"
]);
c.AddMeter("Microsoft.AspNetCore.Hosting", "Microsoft.AspNetCore.Server.Kestrel", "System.Net.Http", "WebApi.Test.Unit");
c.AddOtlpExporter();
})
.WithTracing(c =>
Expand All @@ -51,4 +46,15 @@ public override void ConfigureServices(ConfigureServicesContext context)
context.Services.ConfigureHttpClientDefaults(c => c.AddStandardResilienceHandler());
context.Services.AddMetrics();
}

public override void ApplicationInitialization(ApplicationContext context)
{
var app = context.GetApplicationBuilder() as WebApplication ?? throw new("app is null");
// 配置健康检查端点
app.MapHealthChecks("/health");
app.MapHealthChecks("/alive", new()
{
Predicate = r => r.Tags.Contains("live")
});
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using EasilyNET.AutoDependencyInjection.Contexts;
using EasilyNET.AutoDependencyInjection.Modules;
using WebApi.Test.Unit.Common;

namespace WebApi.Test.Unit;

Expand All @@ -11,7 +12,12 @@ internal sealed class OutPutCachingModule : AppModule
/// <inheritdoc />
public override void ConfigureServices(ConfigureServicesContext context)
{
context.Services.AddOutputCache();
var config = context.Services.GetConfiguration();
context.Services.AddStackExchangeRedisOutputCache(c =>
{
c.Configuration = config["CONNECTIONSTRINGS_GARNET"];
c.InstanceName = Constant.InstanceName;
});
}

/// <inheritdoc />
Expand Down
10 changes: 6 additions & 4 deletions sample/WebApi.Test.Unit/WebApi.Test.Unit.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0-preview.5.24306.11" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-preview.5.24306.11" />
<PackageReference Include="Microsoft.AspNetCore.OutputCaching.StackExchangeRedis" Version="9.0.0-preview.5.24306.11" />
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.0-preview.5.24306.11" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.0.0-preview.5.24311.7" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.8.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.GrpcNetClient" Version="1.8.0-beta.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.8.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.8.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.GrpcNetClient" Version="1.9.0-beta.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.2-dev-00338" />
<PackageReference Include="Serilog.Sinks.Async" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.OpenTelemetry" Version="3.0.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace EasilyNET.AutoDependencyInjection.Abstractions;
/// 对象存取器
/// </summary>
/// <typeparam name="T"></typeparam>
internal abstract class IObjectAccessor<T>
internal interface IObjectAccessor<T>
{
/// <summary>
/// 值
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<!-- ServiceCollectionExtension.cs 已经被 .NET SDK 默认包含 -->
<!-- 只需要为 ServiceCollectionExtension.p.cs 指定嵌套关系 -->
<Compile Update="ServiceCollectionExtension.i.cs">
<DependentUpon>ServiceCollectionExtension.cs</DependentUpon>
</Compile>
<Compile Update="ServiceCollectionExtension.p.cs">
<DependentUpon>ServiceCollectionExtension.cs</DependentUpon>
</Compile>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\EasilyNET.AutoDependencyInjection.Core\EasilyNET.AutoDependencyInjection.Core.csproj" />
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ private static IEnumerable<IAppModule> GetAllEnabledModule(IServiceCollection se
protected void SetServiceProvider(IServiceProvider serviceProvider)
{
ServiceProvider = serviceProvider;
ServiceProvider.GetRequiredService<ObjectAccessor<IServiceProvider>>().Value = ServiceProvider;
ServiceProvider.GetRequiredService<IObjectAccessor<IServiceProvider>>().Value = ServiceProvider;
}

/// <summary>
Expand All @@ -117,7 +117,8 @@ protected void SetServiceProvider(IServiceProvider serviceProvider)
ArgumentNullException.ThrowIfNull(module, nameof(moduleType));
if (!module.Enable)
{
var logger = services.GetService<ILogger<ModuleApplicationBase>>();
var provider = services.BuildServiceProvider();
var logger = provider.GetService<ILogger<ModuleApplicationBase>>();
logger?.LogWarning("{name} is disabled", moduleType.Name);
return null;
}
Expand Down
5 changes: 4 additions & 1 deletion src/EasilyNET.AutoDependencyInjection/ObjectAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@ namespace EasilyNET.AutoDependencyInjection;
/// 对象存取器
/// </summary>
/// <typeparam name="T"></typeparam>
internal sealed class ObjectAccessor<T> : IObjectAccessor<T?>;
internal sealed class ObjectAccessor<T> : IObjectAccessor<T>
{
public T? Value { get; set; }
}
Loading

0 comments on commit e9551da

Please sign in to comment.