You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

287 line
11KB

  1. using AspectCore.Extensions.DependencyInjection;
  2. using HealthMonitor.Common;
  3. using HealthMonitor.Common.helper;
  4. using HealthMonitor.Core.Cache;
  5. using HealthMonitor.Core.Context;
  6. using HealthMonitor.Core.Dal.EfCoreImpl;
  7. using HealthMonitor.Core.Dal;
  8. using HealthMonitor.Core.Dal.Factory;
  9. using HealthMonitor.Core.DbLog;
  10. using HealthMonitor.Core.Operator;
  11. using HealthMonitor.Core.Operator.Redis;
  12. using HealthMonitor.Model.Config;
  13. using HealthMonitor.Service.Biz.db;
  14. using HealthMonitor.WebApi.Configs;
  15. using HealthMonitor.WebApi.DbLog;
  16. using Microsoft.AspNetCore.Mvc;
  17. using Microsoft.EntityFrameworkCore;
  18. using Microsoft.Extensions.Configuration;
  19. using Microsoft.Extensions.DependencyInjection;
  20. using Microsoft.Extensions.Options;
  21. using Microsoft.OpenApi.Models;
  22. using HealthMonitor.WebApi.Swagger;
  23. using HealthMonitor.Service.Cache;
  24. using TelpoDataService.Util.Clients;
  25. using HealthMonitor.Service.Sub;
  26. using HealthMonitor.Service.Resolver;
  27. using HealthMonitor.Service.Resolver.Factory;
  28. using HealthMonitor.Service.Resolver.Interface;
  29. using Serilog;
  30. using Serilog.Core;
  31. using HealthMonitor.WebApi.HttpLog;
  32. using Microsoft.Extensions.Http;
  33. using Microsoft.Extensions.DependencyInjection.Extensions;
  34. namespace HealthMonitor.WebApi
  35. {
  36. public class Program
  37. {
  38. public static void Main(string[] args)
  39. {
  40. //选择配置文件appsetting.json
  41. var config = new ConfigurationBuilder()
  42. .SetBasePath(Directory.GetCurrentDirectory())
  43. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  44. .Build();
  45. Log.Logger = new LoggerConfiguration()
  46. .ReadFrom.Configuration(config).Enrich.WithThreadInfo()
  47. .CreateLogger();
  48. var builder = WebApplication.CreateBuilder(args);
  49. // Add services to the container.
  50. builder.Services.AddHttpClient(Consts.DEFAULT_HTTPCLIENT_NAME, c =>
  51. {
  52. c.Timeout = TimeSpan.FromSeconds(10); //超时限制
  53. c.DefaultRequestHeaders.Add("Accept", "application/json");
  54. //c.DefaultRequestHeaders.Connection.Add("keep-alive");
  55. });
  56. // builder.Services.Configure<TDengineServiceConfig>(builder.Configuration.GetSection("TDengineServiceConfig"));
  57. builder.Services.AddSingleton<HttpHelper>();
  58. builder.Services.AddSingleton<TDengineService>();
  59. builder.Services.AddControllers();
  60. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  61. builder.Services.AddEndpointsApiExplorer();
  62. builder.Services.AddSwaggerGen();
  63. #region scoped MySQL 数据库
  64. builder.Services // gps_card
  65. .AddDbContextPool<GpsCardContext>((sp, options) =>
  66. {
  67. var loggerFactory = sp.GetRequiredService<EfCoreLoggerFactory>();
  68. var mySqlCon = builder.Configuration.GetConnectionString("GpsCard_Connection_String");
  69. var serverVersion = ServerVersion.AutoDetect(mySqlCon);
  70. options.UseMySql(mySqlCon, serverVersion)
  71. .UseLoggerFactory(loggerFactory);
  72. }, poolSize: 64) // health_monitor
  73. .AddDbContextPool<HealthMonitorContext>((sp, options) =>
  74. {
  75. var loggerFactory = sp.GetRequiredService<EfCoreLoggerFactory>();
  76. var mySqlCon = builder.Configuration.GetConnectionString("HealthMonitor_Connection_String");
  77. var serverVersion = ServerVersion.AutoDetect(mySqlCon);
  78. options.UseMySql(mySqlCon, serverVersion)
  79. .UseLoggerFactory(loggerFactory);
  80. }, poolSize: 64); ;
  81. builder.Services
  82. .AddScoped<IGpsCardDataAccessor, EfCoreDataAccessor>(sp =>
  83. {
  84. var context = sp.GetRequiredService<GpsCardContext>();
  85. return new EfCoreDataAccessor(context);
  86. })
  87. .AddScoped<IHealthMonitorDataAccessor, EfCoreDataAccessor>(sp =>
  88. {
  89. var context = sp.GetRequiredService<HealthMonitorContext>();
  90. return new EfCoreDataAccessor(context);
  91. });
  92. //builder.Services.AddDbContextPool<HealthMonitorContext>((sp, options) =>
  93. //{
  94. // var loggerFactory = sp.GetRequiredService<EfCoreLoggerFactory>();
  95. // options.UseMySql(builder.Configuration.GetConnectionString("GpsCard_Connection_String"))
  96. // .UseLoggerFactory(loggerFactory);
  97. //}, poolSize: 64);
  98. //builder.Services.AddScoped<IHealthMonitorDataAccessor, EfCoreDataAccessor>(sp =>
  99. //{
  100. // var context = sp.GetRequiredService<HealthMonitorContext>();
  101. // return new EfCoreDataAccessor(context);
  102. //});
  103. #endregion
  104. #region AOP
  105. //builder.Services.Configure<RedisConfig>(builder.Configuration.GetSection("Redis"));
  106. builder.Services
  107. .Configure<ApiBehaviorOptions>(options =>
  108. {
  109. options.SuppressModelStateInvalidFilter = true;
  110. })
  111. .Configure<RedisConfig>(builder.Configuration.GetSection("Redis"))
  112. .Configure<TDengineServiceConfig>(builder.Configuration.GetSection("TDengineServiceConfig"))
  113. .Configure<ServiceConfig>(builder.Configuration.GetSection("ServiceConfig"));
  114. builder.Services
  115. .AddSingleton<IEfCoreLoggerProvider, EfCoreLogProvider>()
  116. .AddSingleton<IDurableEntityManager, DurableEntityManager>()
  117. .AddSingleton<EfCoreLoggerFactory>(sp =>
  118. {
  119. var provider = sp.GetRequiredService<IEfCoreLoggerProvider>();
  120. return new EfCoreLoggerFactory(new[] { provider });
  121. });
  122. //builder.Services.AddSingleton<IDurableEntityManager, DurableEntityManager>();
  123. //builder.Services.AddSingleton<EfCoreLoggerFactory>(sp =>
  124. //{
  125. // var provider = sp.GetRequiredService<IEfCoreLoggerProvider>();
  126. // return new EfCoreLoggerFactory(new[] { provider });
  127. //});
  128. builder.Services
  129. .AddSingleton<GpsCardAccessorFactory>()
  130. .AddSingleton<HealthMonitorAccessorFactory>();
  131. //builder.Services.AddSingleton<HealthMonitorAccessorFactory>();
  132. builder.Services
  133. .AddSingleton<IGpsCardOperatorManager, GpsCardOperatorRedisManager>()
  134. .AddSingleton<IHealthMonitorOperatorManager, HealthMonitorOperatorRedisManager>();
  135. //builder.Services.AddSingleton<IHealthMonitorOperatorManager, HealthMonitorOperatorRedisManager>();
  136. //用AspectCore替换默认的IOC容器
  137. builder.Host.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
  138. #endregion
  139. #region Cache
  140. builder.Services
  141. .AddSingleton<PersonCacheManager>()
  142. .AddSingleton<BloodPressReferenceValueCacheManager>();
  143. #endregion
  144. #region TelpoDataServices
  145. builder.Services.AddTelpoDataServices(opt =>
  146. {
  147. opt.TelpoDataUrl = builder.Configuration.GetSection("ServiceConfig:TelpoDataUrl").Value;
  148. });
  149. #endregion
  150. #region Worker
  151. builder.Services.AddSingleton<MsgQueueManager>();
  152. builder.Services.AddSingleton<IResolverFactory, ResolverFactory>();
  153. builder.Services.AddSingleton<BloodpressResolver>();
  154. builder.Services.AddSingleton<PackageProcess>();
  155. builder.Services
  156. .AddSingleton<TDengineDataSubcribe>()
  157. .AddHostedService<Worker>();
  158. #endregion
  159. builder.Host.UseSerilog();
  160. builder.Services.Replace(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, CustomLoggingFilter>());
  161. // Register the Swagger generator, defining 1 or more Swagger documents
  162. builder.Services.AddSwaggerGen(c =>
  163. {
  164. //c.SwaggerDoc(AppConsts.SWAGGER_DOC_GpsCard, new OpenApiInfo { Title = "GpsCard模块", Version = "v1", Description = "gps_card数据库服务" }); //分组显示
  165. c.SwaggerDoc(AppConsts.SWAGGER_DOC_HealthMonitor, new OpenApiInfo { Title = "HealthMonitor模块", Version = "v1", Description = "health_monitor数据库服务" }); //分组显示
  166. c.DocumentFilter<EnumDocumentFilter>();
  167. //var utilXmlFile = Path.Combine(AppContext.BaseDirectory, "HealthMonitor.Util.xml");
  168. //var webapiXmlFile = Path.Combine(AppContext.BaseDirectory, "HealthMonitor.WebApi.xml");
  169. //c.IncludeXmlComments(utilXmlFile, true);
  170. //c.IncludeXmlComments(webapiXmlFile, true);
  171. });
  172. var app = builder.Build();
  173. // Configure the HTTP request pipeline.
  174. //if (app.Environment.IsDevelopment())
  175. //{
  176. // app.UseSwagger();
  177. // app.UseSwaggerUI();
  178. //}
  179. string prefix = string.Empty;
  180. //if (!app.Environment.IsDebugOrDevelop())
  181. //{
  182. // prefix = optConfigAppSettings.Value.NginxPrefix;
  183. // if (string.IsNullOrWhiteSpace(prefix)) prefix = SERVICE_PREFIX;
  184. //}
  185. // Enable middleware to serve generated Swagger as a JSON endpoint.
  186. app.UseSwagger(c =>
  187. {
  188. c.PreSerializeFilters.Add((swagger, httpReq) =>
  189. {
  190. var scheme = httpReq.Headers.TryGetValue("X-Forwarded-Proto", out var v2) ? v2.ToString() : httpReq.Scheme;
  191. swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{scheme}://{httpReq.Host}/{prefix}" } };
  192. });
  193. c.RouteTemplate = "/{documentName}/api-docs/";
  194. });
  195. // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
  196. // specifying the Swagger JSON endpoint.
  197. app.UseSwaggerUI(c =>
  198. {
  199. string sub = string.IsNullOrEmpty(prefix) ? "" : $"/{prefix}";
  200. //c.SwaggerEndpoint($"{sub}/{AppConsts.SWAGGER_DOC_GpsCard}/api-docs/", "GpsCard模块"); //分组显示
  201. c.SwaggerEndpoint($"{sub}/{AppConsts.SWAGGER_DOC_HealthMonitor}/api-docs/", "HealthMonitor模块"); //分组显示
  202. c.RoutePrefix = string.Empty;
  203. });
  204. // redis default
  205. var csredis = new CSRedis.CSRedisClient(app.Services.GetService<IOptions<RedisConfig>>()!.Value.ToString());
  206. RedisHelper.Initialization(csredis);
  207. // redis db7
  208. var csredisDb7Con = app.Services.GetService<IOptions<RedisConfig>>()!.Value;
  209. csredisDb7Con.DefaultDatabase = 7;
  210. csredisDb7Con.Prefix = "TELPO";
  211. var csredisDb7 = new CSRedis.CSRedisClient(csredisDb7Con.ToString());
  212. RedisHelperDb7.Initialization(csredisDb7);
  213. app.UseHttpsRedirection();
  214. app.UseAuthorization();
  215. app.MapControllers();
  216. app.Run();
  217. }
  218. }
  219. }