選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

300 行
12KB

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