Comparer les révisions

...

2 Révisions

Auteur SHA1 Message Date
  stevelee de8889eac0 jwk密钥 il y a 2 ans
  stevelee 8145d10bd1 暂时移除鉴权控制 il y a 2 ans
15 fichiers modifiés avec 485 ajouts et 86 suppressions
  1. +16
    -0
      BPA.SaaS.Gateway.Api.sln
  2. +13
    -5
      src/BPA.SaaS.Gateway.Api/BPA.SaaS.Gateway.Api.csproj
  3. +0
    -33
      src/BPA.SaaS.Gateway.Api/Controllers/WeatherForecastController.cs
  4. +52
    -0
      src/BPA.SaaS.Gateway.Api/Filter/BPAAuthorizationFilter.cs
  5. +25
    -11
      src/BPA.SaaS.Gateway.Api/Program.cs
  6. +6
    -19
      src/BPA.SaaS.Gateway.Api/Properties/launchSettings.json
  7. +0
    -13
      src/BPA.SaaS.Gateway.Api/WeatherForecast.cs
  8. +34
    -0
      src/BPA.SaaS.Gateway.Api/ocelot.json
  9. +1
    -0
      src/BPA.SaaS.Gateway.Api/tempkey.jwk
  10. +20
    -5
      src/BPA.SaaS.Gateway.Bootstrap/BPA.SaaS.Gateway.Bootstrap.csproj
  11. +75
    -0
      src/BPA.SaaS.Gateway.Bootstrap/GatewayApiConfig.cs
  12. +107
    -0
      src/BPA.SaaS.Gateway.Bootstrap/SetupBootstrap.cs
  13. +49
    -0
      src/BPA.SaaS.Gateway.Bootstrap/SetupRabbitMqConfig.cs
  14. +46
    -0
      src/BPA.SaaS.Gateway.Bootstrap/SetupRedisConfig.cs
  15. +41
    -0
      src/BPA.SaaS.Gateway.Bootstrap/SetupServiceSDK.cs

+ 16
- 0
BPA.SaaS.Gateway.Api.sln Voir le fichier

@@ -9,6 +9,17 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BPA.SaaS.Gateway.DTO", "src
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BPA.SaaS.Gateway.Bootstrap", "src\BPA.SaaS.Gateway.Bootstrap\BPA.SaaS.Gateway.Bootstrap.csproj", "{2C318709-38D1-4EBC-8950-F6F2047E9E9E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1.Api", "1.Api", "{0CF4098A-00A0-4D5B-973D-C463B52C43BB}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "2.DTO", "2.DTO", "{8A52EC32-7481-4D8C-8FDE-5FB508E86262}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "3.Bootstrap", "3.Bootstrap", "{1B90928A-E822-495B-8CE2-8C620F7D7EC1}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{9646B516-51A7-4D18-BC54-8C83F37E9249}"
ProjectSection(SolutionItems) = preProject
src\nuget.config = src\nuget.config
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -34,4 +45,9 @@ Global
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AE050242-B7E2-4218-BA63-6859CD433A7F}
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{B9E6691B-8AFF-4628-A04C-29B2B1622739} = {0CF4098A-00A0-4D5B-973D-C463B52C43BB}
{CF5A23AA-D96A-427E-A4D5-7BE48C057523} = {8A52EC32-7481-4D8C-8FDE-5FB508E86262}
{2C318709-38D1-4EBC-8950-F6F2047E9E9E} = {1B90928A-E822-495B-8CE2-8C620F7D7EC1}
EndGlobalSection
EndGlobal

+ 13
- 5
src/BPA.SaaS.Gateway.Api/BPA.SaaS.Gateway.Api.csproj Voir le fichier

@@ -1,9 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<Folder Include="Controllers" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BPA.SaaS.Gateway.Bootstrap\BPA.SaaS.Gateway.Bootstrap.csproj" />
</ItemGroup>

</Project>

+ 0
- 33
src/BPA.SaaS.Gateway.Api/Controllers/WeatherForecastController.cs Voir le fichier

@@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Mvc;

namespace BPA.SaaS.Gateway.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

+ 52
- 0
src/BPA.SaaS.Gateway.Api/Filter/BPAAuthorizationFilter.cs Voir le fichier

@@ -0,0 +1,52 @@
using System.Collections.Concurrent;
using BPA.Component.DTOCommon.BaseDTOs;
using BPA.Component.DTOCommon.Langs;
using BPA.Component.WebApiExtensions.Extensions;
using BPA.SaaS.Gateway.Bootstrap;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace BPA.SaaS.Gateway.Api.Filter;

/// <summary>
/// 权限过滤器
/// </summary>
public class BPAAuthorizationFilter : ActionFilterAttribute
{
/// <summary>
/// ConcurrentDictionary
/// </summary>
private readonly ConcurrentDictionary<string, bool> cacheAllowAnonymous = new();

/// <summary>
/// GatewayApiConfig
/// </summary>
private readonly GatewayApiConfig apiConfig;

/// <summary>
/// RWXAuthorization
/// </summary>
/// <param name="apiConfig"></param>
public BPAAuthorizationFilter(GatewayApiConfig apiConfig)
{
this.apiConfig = apiConfig;
}

/// <summary>
/// Action执行之前
/// </summary>
/// <param name="context"></param>
public override void OnActionExecuting(ActionExecutingContext context)
{
}

/// <summary>
/// OnActionExecuted
/// </summary>
/// <param name="context"></param>
public override void OnActionExecuted(ActionExecutedContext context)
{
}
}

+ 25
- 11
src/BPA.SaaS.Gateway.Api/Program.cs Voir le fichier

@@ -1,17 +1,31 @@
var builder = WebApplication.CreateBuilder(args);
using BPA.Component.WebApiExtensions.Extensions;
using BPA.SaaS.Gateway.Bootstrap;

// Add services to the container.
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.SetupConfiguration();
builder.Configuration.AddJsonFile("ocelot.json", true, true);

builder.Services.AddControllers();
// DI
builder.Services.AddBPAMiddlewareServices(args);

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

// Use module
app.UseRouting();
app.UseCors();
app.UseBpaHealthChecks();
app.MapControllers();
// app.UseAuthorization();
app.UseGlobalErrorHandler();
// app.UseOcelot().Wait();

// PreRun
((IApplicationBuilder) app).ApplicationServices.PreHeatRun();

app.Run();
// Run
app.Run();

+ 6
- 19
src/BPA.SaaS.Gateway.Api/Properties/launchSettings.json Voir le fichier

@@ -1,30 +1,17 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:1296",
"sslPort": 44300
}
},
"profiles": {
"BPA.SaaS.Gateway.Api": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:7001;http://localhost:5001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"launchUrl": "swagger",
"applicationUrl": "http://localhost:8080",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
"ASPNETCORE_ENVIRONMENT": "Development",
"APOLLO_META_SERVER_URL": "http://10.2.1.21:28080",
"APOLLO_COMMON_NAMESPACE": "Dev.Common",
"APP_NAME": "BPA-GATEWAY-API"
}
}
}


+ 0
- 13
src/BPA.SaaS.Gateway.Api/WeatherForecast.cs Voir le fichier

@@ -1,13 +0,0 @@
namespace BPA.SaaS.Gateway.Api
{
public class WeatherForecast
{
public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }
}
}

+ 34
- 0
src/BPA.SaaS.Gateway.Api/ocelot.json Voir le fichier

@@ -0,0 +1,34 @@
{
"Routes": [
{
"DownstreamPathTemplate": "/connect/token",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8080
}
],
"UpstreamPathTemplate": "/token",
"UpstreamHttpMethod": [
"Post"
]
},
{
"DownstreamPathTemplate": "/stock/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 8080
}
],
"UpstreamPathTemplate": "/stock/{everything}",
"UpstreamHttpMethod": [
"Post",
"Get"
]
}
]
}


+ 1
- 0
src/BPA.SaaS.Gateway.Api/tempkey.jwk Voir le fichier

@@ -0,0 +1 @@
{"alg":"RS256","d":"jJ62y7Sq87ONjzSU2nWNYdPZzJG7g-qgu2C63FeWWtrz7qRA1n6I_vEEWlpswDmcdInFKGFlRa6BeH8hdo2I3osO_97yklCDsFExCvxAye8WytzlblBGKmcfm3iJUoD9waJ8k7koYgPTEiFCoR4DoV8d73-sez8QrZ31gzpyUgAW56wTBGahyQ3-h8QUKcOiL_3cjdB7AhvJH3-oiD3vGKXMrJZ_Vx_wqMbPJdBTi1dv0FaPdaxU5eQ7QztgSargyvfRYKQrVBt-mvmimFw7vP7nGi0w99yLkwcCJUZ0oUD1uMmrJrSk4QebgJsPGa7vjPB2IrvNcP-nqgMUStro6Q","dp":"vtzp6YU9ZGZsjs9l-vZKEU1zTuwQPOmbruWkzTwzQSINlnctQHVLbA0D-P4WImpHwYM5gDaFsyTpodAwsmhOcxV2Vx9b_g1vFWe8XToROMdlWbSsmzo-Z0wxOAhD45s8aEWyLDkMnERCS8Z5VEssn-_zcG7ZKOmDFZWo0EbL0-U","dq":"iAyX0BQoRxEjxWahkWPnLR_CV4tVVAmIf2sZa-S_rvpjzXzx0pCpq90Ea-Aac_o5q1wrqbnpsP0bX3WqZ4gaZSrTr_bTFmAT1M2lmj8nfJ2OZdm_FqRi44F583myCjZXMa-g7RGBrcjWFSJscHiScS1un2ZgeNWez8sDZd-9-qU","e":"AQAB","kid":"FE1C4DF831C68E2D23278BB7B09B49D3","kty":"RSA","n":"qEnXCqWJbkVcYIjleIlJvKuZkXxzxhlSVQgZCwjZEg9iOXaT8QAZt9l-yUpCYB_ZBb3ehRyzlPJWGsxyRy7KstZ8YaMYeUJmh_JRkPiHVemVSxp9F-CbQJ7qEZi1u2dhEefQTxYrFC_IAV3YUBwlSHsvuRTzxmxhLrHTCMKlahHN-1QKj1Oi5rfufK9P7hzwescfd6RvU7rQvaESugH68_fowmaddZRVTg_2JpmCAS7LnAKYipXZY39NlQp8NXZ9w9z36dMdX93x72eQU4Tvm4JFumidJaadeOJMkm9LmLEMehbXT8KZlA6IPu_ykPwlHaDidh7DZTjvgzCf1v5DMQ","p":"3tWZkEzLTAqMXC1MdEIF0T5O_WXLxwUsoarO5XizarHWBwIpD6wkBBaVcrl_42X5UozAUtGu2UGzzA4OzmCFzYFswLLcAXdDPnuZGdUtxfA2Sxyfi22PZhXWjhgdmzVnWSGV7l_m_wKAcUlm6C_xv7e0MA9d-Q_ciIbpNyKGCWc","q":"wVXwgWHMkkmIbIBr9J4YUaj62x4UfZ-X9S84pc8EDPqFHJ0nzDv5XSvjOoskg8iy_pmq-DQ-GSZ-E7NcySMPQAJyegZBmNYDd_yuyeHVojdqXVLnTODNB8MlrJmjJInk46DCfOkW90yGaUWEoQGU4DbjD9Np8QvSVZswk3OPN6c","qi":"kNCJq6BUXMb8vX4CyVava8M-924MtPVXQDmCBpCtZP49MspRTCG8LwlXBEpsata0WOc-QA8A1c77_1Y70JAYXK9NkX-j4TOdxNsLzZn9q3Q939biU1CHIpw-bzi-VeOVd48ri8qrAll7t1oqXk-z3cxLbhJ4P4fyX9R87v_xbyo"}

+ 20
- 5
src/BPA.SaaS.Gateway.Bootstrap/BPA.SaaS.Gateway.Bootstrap.csproj Voir le fichier

@@ -1,9 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BPA.Component.ApolloClient" Version="1.0.5"/>
<PackageReference Include="BPA.Component.DTOCommon" Version="1.0.6"/>
<PackageReference Include="BPA.Component.Extensions" Version="1.0.4"/>
<PackageReference Include="BPA.Component.LogClient" Version="1.0.3"/>
<PackageReference Include="BPA.Component.RabbitMQClient" Version="1.0.7"/>
<PackageReference Include="BPA.Component.RedisClient" Version="1.0.3"/>
<PackageReference Include="BPA.Component.SDKCommon" Version="1.0.3"/>
<PackageReference Include="BPA.Component.WebApiExtensions" Version="1.0.8"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3"/>
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.2.3"/>
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.2.3"/>
<!-- <PackageReference Include="Ocelot" Version="18.0.0"/>-->
</ItemGroup>

</Project>

+ 75
- 0
src/BPA.SaaS.Gateway.Bootstrap/GatewayApiConfig.cs Voir le fichier

@@ -0,0 +1,75 @@
using BPA.Component.ApolloClient;
using BPA.Component.RabbitMQClient.Connection;
using Com.Ctrip.Framework.Apollo;
using Microsoft.Extensions.Configuration;

namespace BPA.SaaS.Gateway.Bootstrap;

public class GatewayApiConfig : ApolloBPAConfig<GatewayApiConfig>
{
/// <summary>
/// 允许跨域的地址
/// </summary>
[AutoWrite]
public string[] CoreWithOrigins { private set; get; }

/// <summary>
/// 附件API服务URL
/// </summary>
[AutoWrite]
public string AnnexApiUrl { protected set; get; }

/// <summary>
/// web UI host url
/// </summary>
[AutoWrite]
public string WebUIHostUrl { set; get; }

/// <summary>
/// Mobile UI host url
/// </summary>
[AutoWrite]
public string MobileUIHostUrl { set; get; }

/// <summary>
/// 网关 host
/// </summary>
[AutoWrite]
public string GetewayHostUrl { set; get; }

/// <summary>
/// 是否允许密码登陆
/// </summary>
[AutoWrite]
public bool IsAllowPasswordLogin { set; get; }

/// <summary>
/// 单位时间限制的次数, 默认10次
/// </summary>
[AutoWrite]
public int RequestLimitFrequency { get; set; } = 10;

/// <summary>
/// 限制的时间周期 秒,默认10秒
/// </summary>
[AutoWrite]
public int RequestLimitSeconds { get; set; } = 10;

/// <summary>
/// 共享CookieDomain
/// </summary>
[AutoWrite]
public string CookieDomain { set; get; }
/// <summary>
/// RabbitMQ配置
/// </summary>
[AutoWrite]
public new RabbitMqConnectionConfig RabbitMqConfig { get; set; }

#pragma warning disable CS8618
public GatewayApiConfig(ApolloConfigurationManager apolloConfigurationManager, IConfiguration configuration) : base(apolloConfigurationManager, configuration)
#pragma warning restore CS8618
{
}
}

+ 107
- 0
src/BPA.SaaS.Gateway.Bootstrap/SetupBootstrap.cs Voir le fichier

@@ -0,0 +1,107 @@
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using BPA.Component.ApolloClient;
using BPA.Component.Extensions;
using BPA.Component.LogClient.Extensions;
using BPA.Component.WebApiExtensions.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
// using Ocelot.DependencyInjection;
using IPAddress = System.Net.IPAddress;

namespace BPA.SaaS.Gateway.Bootstrap;

/// <summary>
/// 启动配置
/// </summary>
public static class SetupBootstrap
{
private static IConfiguration _configuration;

/// <summary>
/// 添加配置中心
/// </summary>
/// <param name="configuration"></param>
public static IConfiguration SetupConfiguration(this IConfiguration configuration)
{
_configuration = configuration;

// 初始化化 apollo配置
return configuration.AddApolloConfiguration();
}

/// <summary>
/// DI Inject
/// </summary>
public static IServiceCollection AddBPAMiddlewareServices(this IServiceCollection services, string[] args)
{
if (services == null) throw new ArgumentNullException(nameof(services));

services.AddApollo<GatewayApiConfig>();
services.AddBPALog();
services.AddRedis();
services.AddRabbitMQ();
services.AddHttpContextAccessor();
services.AddControllers(options => { options.AddDefaultMvcOptions(); });
services.AddEndpointsApiExplorer();
services.AddServiceSDK(_configuration);
services.AddHealthChecks();
services.AddResponseCaching();
// services.AddOcelot(_configuration);
// services.AddAuthentication();
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "BPA.Gateway.Api",
Description = "BPA.Gateway.Api",
Version = "v1"
});
options.CustomSchemaIds(type => type.GetDescribe(true, "BPA.", "BPA.Component."));
});

return services;
}

/// <summary>
/// pre run
/// </summary>
/// <param name="serviceProvider"></param>
public static void PreHeatRun(this IServiceProvider serviceProvider)
{
serviceProvider.GetService<GatewayApiConfig>();
serviceProvider.PreHeatRunRedis();
serviceProvider.PreHeatRunRabbitMQ();
}

/// <summary>
/// APP健康检查
/// </summary>
/// <param name="app"></param>
public static void UseBpaHealthChecks(this IApplicationBuilder app)
{
var ips = new List<dynamic>();
foreach (var network in NetworkInterface.GetAllNetworkInterfaces())
{
var ipAddress = network.GetIPProperties()
.UnicastAddresses
.FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))
?.Address.ToString();
if (ipAddress == null)
continue;
ips.Add(new {name = network.Name, ip = ipAddress});
}

var ipsJson = ips.ToJson();

app.UseHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = (httpContext, _) => httpContext.Response.WriteAsync(ipsJson, Encoding.UTF8)
});
}
}

+ 49
- 0
src/BPA.SaaS.Gateway.Bootstrap/SetupRabbitMqConfig.cs Voir le fichier

@@ -0,0 +1,49 @@
using BPA.Component.RabbitMQClient.Extensions;
using BPA.Component.RabbitMQClient.Provider;
using Microsoft.Extensions.DependencyInjection;

namespace BPA.SaaS.Gateway.Bootstrap
{
/// <summary>
/// RabbitMQ配置
/// </summary>
public static class SetupRabbitMqConfig
{
/// <summary>
/// 使用消息队列
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddRabbitMQ(this IServiceCollection services)
{
//注入 RabbitMQProvider
services.AddRabbitMQProvider(sp => sp.GetService<GatewayApiConfig>()?.RabbitMqConfig);
// //注入 业务日志 生产者 单例
// services.UseRabbitMQProducer<CreateBizLogProducer, CreateBizLogMsgBody>();
// //注入 消息 生产者 单例
// services.UseRabbitMQProducer<BatchAddMessageProduct, BatchAddMessageMsgBody>();

return services;
}

/// <summary>
/// 预热消息队列
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public static IServiceProvider PreHeatRunRabbitMQ(this IServiceProvider serviceProvider)
{
//获取rabbitMqProvider
var rabbitMqProvider = serviceProvider.UseRabbitMQProvider<RabbitMQProvider>();

// //创建交换机配置对象
// var createBizLogExchangeConfig = rabbitMqProvider.BuildExchangeConfig(MqNameConfig.CreateBizLogExchange);
// //启用交换机
// createBizLogExchangeConfig.UseExchange();
// //启用生产者
// createBizLogExchangeConfig.UseProducer<CreateBizLogMsgBody, CreateBizLogProducer>();

return serviceProvider;
}
}
}

+ 46
- 0
src/BPA.SaaS.Gateway.Bootstrap/SetupRedisConfig.cs Voir le fichier

@@ -0,0 +1,46 @@
using BPA.Component.RedisClient;
using Microsoft.Extensions.DependencyInjection;

namespace BPA.SaaS.Gateway.Bootstrap;

/// <summary>
/// redis DI配置
/// </summary>
public static class SetupRedisConfig
{
/// <summary>
/// 注入redis
/// </summary>
/// <param name="services"></param>
public static void AddRedis(this IServiceCollection services)
{
services.UseRedisSingleton(sp => GetRedisSingletonConnectionString(sp.GetService<GatewayApiConfig>()!));
}

/// <summary>
/// 预热redis
/// </summary>
/// <param name="serviceProvider"></param>
public static void PreHeatRunRedis(this IServiceProvider serviceProvider)
{
var config = serviceProvider.GetService<GatewayApiConfig>();

// 添加配置改变时的事件
if (config != null)
config.OnConfigChange += (stockWebApiConfig, key, _, _, _) =>
{
if (nameof(stockWebApiConfig.RedisConfig) != key) return;
var conStr = GetRedisSingletonConnectionString(stockWebApiConfig);

//单个redis时 配置变化 触发生成新的实例
RedisConfigExtensions.OnRedisSingletonConnectionStringChange(conStr);
};
}

/// <summary>
/// 获取单例 Redis 连接字符串
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
private static string GetRedisSingletonConnectionString(GatewayApiConfig config) => config.RedisConfig[new Random().Next(0, config.RedisConfig.Count)];
}

+ 41
- 0
src/BPA.SaaS.Gateway.Bootstrap/SetupServiceSDK.cs Voir le fichier

@@ -0,0 +1,41 @@
using BPA.Component.DTOCommon.Langs;
using BPA.Component.SDKCommon;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace BPA.SaaS.Gateway.Bootstrap;

/// <summary>
/// 其他SDK服务
/// </summary>
public static class SetupServiceSDK
{
/// <summary>
/// 注入其他SDK
/// </summary>
/// <param name="services"></param>
/// <param name="configuration"></param>
public static void AddServiceSDK(this IServiceCollection services, IConfiguration configuration)
{
// 初始化sdk配置和语言获取
services.AddApiSDK(sp => /*sp.GetService<IHttpContextAccessor>()?.HttpContext?.Request.GetLanguage() ??*/ LangType.Zn);

// 获取当前API启动时定义的环境
var environment = configuration.GetValue<string>("ASPNETCORE_ENVIRONMENT");

// 环境选择
switch (environment)
{
case "Development":
// services.UseApiSDK<WebApi2SDK>(_ => "http://serviceName");
// services.AddApiSDK<WebApi2SDK>(_ => "http://192.168.1.8:5012");
break;
case "Production":
// services.AddApiSDK<WebApi2SDK>(_ => "http://[domainName].com:[80]/[serviceName]");
break;
case "Testing":
// services.AddApiSDK<WebApi2SDK>(_ => "http://test.[domainName].com:[80]/[serviceName]/");
break;
}
}
}

Chargement…
Annuler
Enregistrer