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.

296 satır
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. .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<BloodPressReferenceValueCacheManager>();
  147. #endregion
  148. #region TelpoDataServices
  149. builder.Services.AddTelpoDataServices(opt =>
  150. {
  151. opt.TelpoDataUrl = builder.Configuration.GetSection("ServiceConfig:TelpoDataUrl").Value;
  152. });
  153. #endregion
  154. #region Worker
  155. builder.Services.AddSingleton<MsgQueueManager>();
  156. builder.Services.AddSingleton<IResolverFactory, ResolverFactory>();
  157. builder.Services.AddSingleton<BloodpressResolver>();
  158. builder.Services.AddSingleton<PackageProcess>();
  159. builder.Services
  160. .AddSingleton<TDengineDataSubcribe>()
  161. .AddSingleton<IotWebApiService>()
  162. .AddSingleton<EtcdService>()
  163. .AddHostedService<Worker>();
  164. #endregion
  165. builder.Host.UseSerilog();
  166. builder.Services.Replace(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, CustomLoggingFilter>());
  167. // Register the Swagger generator, defining 1 or more Swagger documents
  168. builder.Services.AddSwaggerGen(c =>
  169. {
  170. //c.SwaggerDoc(AppConsts.SWAGGER_DOC_GpsCard, new OpenApiInfo { Title = "GpsCard模块", Version = "v1", Description = "gps_card数据库服务" }); //分组显示
  171. c.SwaggerDoc(AppConsts.SWAGGER_DOC_HealthMonitor, new OpenApiInfo { Title = "HealthMonitor模块", Version = "v1", Description = "health_monitor数据库服务" }); //分组显示
  172. c.DocumentFilter<EnumDocumentFilter>();
  173. //var utilXmlFile = Path.Combine(AppContext.BaseDirectory, "HealthMonitor.Util.xml");
  174. //var webapiXmlFile = Path.Combine(AppContext.BaseDirectory, "HealthMonitor.WebApi.xml");
  175. //c.IncludeXmlComments(utilXmlFile, true);
  176. //c.IncludeXmlComments(webapiXmlFile, true);
  177. });
  178. var app = builder.Build();
  179. // Configure the HTTP request pipeline.
  180. //if (app.Environment.IsDevelopment())
  181. //{
  182. // app.UseSwagger();
  183. // app.UseSwaggerUI();
  184. //}
  185. string prefix = string.Empty;
  186. if (!app.Environment.IsDevelopment())
  187. {
  188. //prefix = optConfigAppSettings.Value.NginxPrefix;
  189. //if (string.IsNullOrWhiteSpace(prefix)) prefix = SERVICE_PREFIX;
  190. prefix = "hm";
  191. }
  192. // Enable middleware to serve generated Swagger as a JSON endpoint.
  193. app.UseSwagger(c =>
  194. {
  195. c.PreSerializeFilters.Add((swagger, httpReq) =>
  196. {
  197. var scheme = httpReq.Headers.TryGetValue("X-Forwarded-Proto", out var v2) ? v2.ToString() : httpReq.Scheme;
  198. swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{scheme}://{httpReq.Host}/{prefix}" } };
  199. });
  200. c.RouteTemplate = "/{documentName}/api-docs/";
  201. });
  202. // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
  203. // specifying the Swagger JSON endpoint.
  204. app.UseSwaggerUI(c =>
  205. {
  206. string sub = string.IsNullOrEmpty(prefix) ? "" : $"/{prefix}";
  207. //c.SwaggerEndpoint($"{sub}/{AppConsts.SWAGGER_DOC_GpsCard}/api-docs/", "GpsCard模块"); //分组显示
  208. c.SwaggerEndpoint($"{sub}/{AppConsts.SWAGGER_DOC_HealthMonitor}/api-docs/", "HealthMonitor模块"); //分组显示
  209. c.RoutePrefix = string.Empty;
  210. });
  211. // redis default
  212. var csredis = new CSRedis.CSRedisClient(app.Services.GetService<IOptions<RedisConfig>>()!.Value.ToString());
  213. RedisHelper.Initialization(csredis);
  214. // redis db7
  215. var csredisDb7Con = app.Services.GetService<IOptions<RedisConfig>>()!.Value;
  216. csredisDb7Con.DefaultDatabase = 7;
  217. csredisDb7Con.Prefix = "TELPO";
  218. var csredisDb7 = new CSRedis.CSRedisClient(csredisDb7Con.ToString());
  219. RedisHelperDb7.Initialization(csredisDb7);
  220. app.UseHttpsRedirection();
  221. app.UseAuthorization();
  222. app.UseMiddleware<LoggingMiddleware>();
  223. app.MapControllers();
  224. app.Run();
  225. }
  226. }
  227. }