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.

295 lines
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(10); //超时限制
  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. builder.Services
  118. .AddSingleton<IEfCoreLoggerProvider, EfCoreLogProvider>()
  119. .AddSingleton<IDurableEntityManager, DurableEntityManager>()
  120. .AddSingleton<EfCoreLoggerFactory>(sp =>
  121. {
  122. var provider = sp.GetRequiredService<IEfCoreLoggerProvider>();
  123. return new EfCoreLoggerFactory(new[] { provider });
  124. });
  125. //builder.Services.AddSingleton<IDurableEntityManager, DurableEntityManager>();
  126. //builder.Services.AddSingleton<EfCoreLoggerFactory>(sp =>
  127. //{
  128. // var provider = sp.GetRequiredService<IEfCoreLoggerProvider>();
  129. // return new EfCoreLoggerFactory(new[] { provider });
  130. //});
  131. builder.Services
  132. .AddSingleton<GpsCardAccessorFactory>()
  133. .AddSingleton<HealthMonitorAccessorFactory>();
  134. //builder.Services.AddSingleton<HealthMonitorAccessorFactory>();
  135. builder.Services
  136. .AddSingleton<IGpsCardOperatorManager, GpsCardOperatorRedisManager>()
  137. .AddSingleton<IHealthMonitorOperatorManager, HealthMonitorOperatorRedisManager>();
  138. //builder.Services.AddSingleton<IHealthMonitorOperatorManager, HealthMonitorOperatorRedisManager>();
  139. //用AspectCore替换默认的IOC容器
  140. builder.Host.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
  141. #endregion
  142. #region Cache
  143. builder.Services
  144. .AddSingleton<PersonCacheManager>()
  145. .AddSingleton<BloodPressReferenceValueCacheManager>();
  146. #endregion
  147. #region TelpoDataServices
  148. builder.Services.AddTelpoDataServices(opt =>
  149. {
  150. opt.TelpoDataUrl = builder.Configuration.GetSection("ServiceConfig:TelpoDataUrl").Value;
  151. });
  152. #endregion
  153. #region Worker
  154. builder.Services.AddSingleton<MsgQueueManager>();
  155. builder.Services.AddSingleton<IResolverFactory, ResolverFactory>();
  156. builder.Services.AddSingleton<BloodpressResolver>();
  157. builder.Services.AddSingleton<PackageProcess>();
  158. builder.Services
  159. .AddSingleton<TDengineDataSubcribe>()
  160. .AddSingleton<IotWebApiService>()
  161. .AddSingleton<EtcdService>()
  162. .AddHostedService<Worker>();
  163. #endregion
  164. builder.Host.UseSerilog();
  165. builder.Services.Replace(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, CustomLoggingFilter>());
  166. // Register the Swagger generator, defining 1 or more Swagger documents
  167. builder.Services.AddSwaggerGen(c =>
  168. {
  169. //c.SwaggerDoc(AppConsts.SWAGGER_DOC_GpsCard, new OpenApiInfo { Title = "GpsCard模块", Version = "v1", Description = "gps_card数据库服务" }); //分组显示
  170. c.SwaggerDoc(AppConsts.SWAGGER_DOC_HealthMonitor, new OpenApiInfo { Title = "HealthMonitor模块", Version = "v1", Description = "health_monitor数据库服务" }); //分组显示
  171. c.DocumentFilter<EnumDocumentFilter>();
  172. //var utilXmlFile = Path.Combine(AppContext.BaseDirectory, "HealthMonitor.Util.xml");
  173. //var webapiXmlFile = Path.Combine(AppContext.BaseDirectory, "HealthMonitor.WebApi.xml");
  174. //c.IncludeXmlComments(utilXmlFile, true);
  175. //c.IncludeXmlComments(webapiXmlFile, true);
  176. });
  177. var app = builder.Build();
  178. // Configure the HTTP request pipeline.
  179. //if (app.Environment.IsDevelopment())
  180. //{
  181. // app.UseSwagger();
  182. // app.UseSwaggerUI();
  183. //}
  184. string prefix = string.Empty;
  185. if (!app.Environment.IsDevelopment())
  186. {
  187. //prefix = optConfigAppSettings.Value.NginxPrefix;
  188. //if (string.IsNullOrWhiteSpace(prefix)) prefix = SERVICE_PREFIX;
  189. prefix = "hm";
  190. }
  191. // Enable middleware to serve generated Swagger as a JSON endpoint.
  192. app.UseSwagger(c =>
  193. {
  194. c.PreSerializeFilters.Add((swagger, httpReq) =>
  195. {
  196. var scheme = httpReq.Headers.TryGetValue("X-Forwarded-Proto", out var v2) ? v2.ToString() : httpReq.Scheme;
  197. swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{scheme}://{httpReq.Host}/{prefix}" } };
  198. });
  199. c.RouteTemplate = "/{documentName}/api-docs/";
  200. });
  201. // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
  202. // specifying the Swagger JSON endpoint.
  203. app.UseSwaggerUI(c =>
  204. {
  205. string sub = string.IsNullOrEmpty(prefix) ? "" : $"/{prefix}";
  206. //c.SwaggerEndpoint($"{sub}/{AppConsts.SWAGGER_DOC_GpsCard}/api-docs/", "GpsCard模块"); //分组显示
  207. c.SwaggerEndpoint($"{sub}/{AppConsts.SWAGGER_DOC_HealthMonitor}/api-docs/", "HealthMonitor模块"); //分组显示
  208. c.RoutePrefix = string.Empty;
  209. });
  210. // redis default
  211. var csredis = new CSRedis.CSRedisClient(app.Services.GetService<IOptions<RedisConfig>>()!.Value.ToString());
  212. RedisHelper.Initialization(csredis);
  213. // redis db7
  214. var csredisDb7Con = app.Services.GetService<IOptions<RedisConfig>>()!.Value;
  215. csredisDb7Con.DefaultDatabase = 7;
  216. csredisDb7Con.Prefix = "TELPO";
  217. var csredisDb7 = new CSRedis.CSRedisClient(csredisDb7Con.ToString());
  218. RedisHelperDb7.Initialization(csredisDb7);
  219. app.UseHttpsRedirection();
  220. app.UseAuthorization();
  221. app.UseMiddleware<LoggingMiddleware>();
  222. app.MapControllers();
  223. app.Run();
  224. }
  225. }
  226. }