public static void Main(string[] args) { var core_env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var config = new ConfigurationBuilder() .SetBasePath(Environment.CurrentDirectory) //指定配置文件所在的目录 .AddJsonFile($"appsettings.{(string.IsNullOrEmpty(core_env) ? core_env : core_env + ".")}json", optional: true, reloadOnChange: true) .Build(); ConfigManagerConf.SetConfiguration(config);//Config配置文件注册 var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var catalogContext = services.GetRequiredService <STSysContext>(); STSysContextSeed.SeedAsync(catalogContext, loggerFactory).Wait(); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB."); } }; host.Run(); }
public static IApplicationBuilder UseExceptionLessLog(this IApplicationBuilder app) { app.UseExceptionless(ConfigManagerConf.GetValue("Exceptionless:ApiKey")); var submittingEvent = app.ApplicationServices.GetRequiredService <ISubmittingEvent>(); ExceptionlessClient.Default.SubmittingEvent += submittingEvent.OnSubmittingEvent; return(app); }
private static string AddTenant(this IApplicationBuilder app, string serviceName, string version, Uri uri, Uri healthCheckUri = null, IEnumerable <string> tags = null) { if (app == null) { throw new ArgumentNullException(nameof(app)); } var consulClient = new ConsulClient(configuration => { configuration.Address = new Uri(ConfigManagerConf.GetValue("ServiceDiscovery:Consul:HttpEndpoint")); }); string check = healthCheckUri?.ToString() ?? $"{uri}".TrimEnd('/') + "/health"; string versionLabel = $"{VERSION_PREFIX}{version}"; var tagList = (tags ?? Enumerable.Empty <string>()).ToList(); tagList.Add(versionLabel); var registration = new AgentServiceRegistration() { ID = Guid.NewGuid().ToString(), Name = serviceName, Address = uri.Host, Port = uri.Port, Tags = tagList.ToArray(), Check = new AgentServiceCheck { // 3.1、consul健康检查超时间 Timeout = TimeSpan.FromSeconds(10), // 3.2、服务停止_后注销服务 DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(10), // 3.3、consul健康检查地址 HTTP = check, // 3.4 consul健康检查间隔时间 Interval = TimeSpan.FromSeconds(10), } }; string id = registration.ID; var allService = consulClient.Catalog.Service(ConfigManagerConf.GetValue("ServiceDiscovery:ServiceName")).GetAwaiter().GetResult(); var regService = allService.Response.FirstOrDefault(x => x.Address == registration.Address && x.ServicePort == registration.Port); if (regService == null) { Console.WriteLine($"注册的serviceid:{registration.ID}"); consulClient.Agent.ServiceRegister(registration).Wait(); } else { id = regService.ServiceID; } consulClient.Dispose(); return(id); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); ConfigManagerConf.SetConfiguration(Configuration); services.AddServiceDiscoveryOptions(); services.AddConsulService(); services.AddHttpClient(); services.AddIdentityServer4Auth(); services.AddOcelot().AddConsul(); }
public static void Main(string[] args) { var core_env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); //根据 <环境变量> 读取不同的配置文件 //VS设置调试环境变量: 项目->属性->调试->环境变量 //docker -env key=value 设置<环境变量> var config = new ConfigurationBuilder() .SetBasePath(Environment.CurrentDirectory) //指定配置文件所在的目录 .AddJsonFile($"appsettings.{(string.IsNullOrEmpty(core_env) ? core_env : core_env + ".")}json", optional: true, reloadOnChange: true) .Build(); //加载指定的配置文件<环境变量:ASPNETCORE_ENVIRONMENT>未配置,则读取 appsettings.json Console.WriteLine($"read setting json: appsettings.{(string.IsNullOrEmpty(core_env) ? core_env : core_env + ".")}json"); core_env = null; #region 初始化区域模块 //配置中心: 读取appsettings.json -> 可扩展配置中心 //读取配置 ConfigManagerConf.GetValue("key") ,key 使用冒号寻找下级(Core配置文件): Logging:Debug ConfigManagerConf.SetConfiguration(config);//Config配置文件注册 Console.WriteLine("read setting end."); Console.WriteLine("ioc register start... attribute aop"); IocContainer.Container.RegisterAssembly("Standard.Examples", "IStandard.Examples"); // Ioc注册 实现dll , 接口类 IocContainer.Container.Build(); //Ioc 注册后编译 Console.WriteLine("ioc register end."); Console.WriteLine("rabbitmq customer start..."); Console.WriteLine("attribute TopSubscribeAttribute loding..."); IocContainer.Container.RabbitBuild(); //注册rabbitmq Console.WriteLine("rabbitmq customer end."); Console.WriteLine("set mysql connection start."); DBContextEntity.DbContext.Configure(ConfigManagerConf.GetValue("DB:mysql"));//mysql连接初始化 Console.WriteLine("set mysql connection end."); #endregion var build = WebHost.CreateDefaultBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup <Startup>() .Build(); //启动同步监控 build.Run(); #region 初始化释放模块 IocContainer.Container.RabbitDispose(); #endregion }
public static IServiceCollection WebServiceExtensions(this IServiceCollection services, IConfiguration configuration) { ConfigManagerConf.SetConfiguration(configuration); services.AddSwagger(); services.AddServiceDiscoveryOptions(); services.AddConsulService(); services.AddExceptionLessLog(); services.AddRabbitMQ(); services.AddCSRedis(); return(services); }
public static void Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) //指定配置文件所在的目录 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); //指定加载的配 #if DEBUG //本地运行开发 config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) //指定配置文件所在的目录 .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true) .Build(); #endif #region 初始化区域模块 //设置配置文件 ConfigManagerConf.SetConfiguration(config);//Config配置文件注册 #region 获取配置文件值(value), 引用类型测试 -> Etcd 及时更新 //List<string> kd= ConfigManagerConf.GetReferenceValue("99999"); //while (true) //{ // Console.WriteLine(kd[0]); // Console.WriteLine("按任意键下一次输出"); // Console.ReadLine(); //} #endregion IocContainer.Container.RegisterAssembly("Standard.Examples", "IStandard.Examples"); // Ioc注册 实现dll , 接口类 IocContainer.Container.Build(); //Ioc 注册后编译 IocContainer.Container.RabbitBuild(); //注册rabbitmq DBContextEntity.DbContext.Configure(ConfigManagerConf.GetValue("DB:mysql")); //mysql连接初始化 #endregion var build = WebHost.CreateDefaultBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup <Startup>() .Build(); //启动同步监控 build.Run(); #region 初始化释放模块 IocContainer.Container.RabbitDispose(); #endregion }
public static IServiceCollection AddServiceDiscoveryOptions(this IServiceCollection services) { services.Configure <ServiceDiscoveryOptions>((o) => { o.ConnectionStringName = ConfigManagerConf.GetValue("ServiceDiscovery:ConnectionStringName"); o.Endpoints = ConfigManagerConf.GetReferenceValue("ServiceDiscovery:Consul:DnsEndpoint").ToArray(); o.HealthCheckTemplate = ConfigManagerConf.GetValue("ServiceDiscovery:HealthCheckTemplate"); o.Namespace = ConfigManagerConf.GetValue("ServiceDiscovery:Namespace"); o.ServiceName = ConfigManagerConf.GetValue("ServiceDiscovery:ServiceName"); o.Version = ConfigManagerConf.GetValue("ServiceDiscovery:Version"); }); services.AddHealthChecks(); return(services); }
/// <summary> /// 注册 /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <returns></returns> public static IServiceCollection AddConsulService(this IServiceCollection services) { services.Configure <ConsulOptions>(o => { o.DnsEndpoint = new DnsEndpoint() { Address = ConfigManagerConf.GetValue("ServiceDiscovery:Consul:DnsEndpoint:Address"), Port = Convert.ToInt32(ConfigManagerConf.GetValue("ServiceDiscovery:Consul:DnsEndpoint:Port")) }; o.HttpEndpoint = ConfigManagerConf.GetValue("ServiceDiscovery:Consul:HttpEndpoint"); }); services.TryAddSingleton <IRegistryService, ConsulRegistryService>(); return(services); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(options => { //设置时间格式 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize; //忽略空值 options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; });; ConfigManagerConf.SetConfiguration(Configuration); services.AddServiceDiscoveryOptions(); services.AddConsulService(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ConfigManagerConf.SetConfiguration(Configuration); services.AddIdentityServer() // 注册IdentityServer4 .AddDeveloperSigningCredential() // 采用开发者凭证 .AddInMemoryApiResources(AuthConfig.GetApiResources()) // 添加Api资源 .AddInMemoryClients(AuthConfig.GetClients()) // 添加客户端 .AddInMemoryIdentityResources(AuthConfig.GetIdentityResources()) // 添加身份资源 .AddResourceOwnerValidator <ResourceOwnerValidator>(); //身份验证 services.AddCsRedisConf(); services.AddServiceDiscoveryOptions(); services.AddConsulService(); services.AddControllers(); }
public RabbitMQConsumerClientFactory(RabbitMQOptions options) { if (options != null) { _rabbitMQOptions = options; return; } _rabbitMQOptions = new RabbitMQOptions { HostName = ConfigManagerConf.GetValue("rabbitmq:HostName"), Password = ConfigManagerConf.GetValue("rabbitmq:Password"), UserName = ConfigManagerConf.GetValue("rabbitmq:UserName"), VirtualHost = ConfigManagerConf.GetValue("rabbitmq:VirtualHost"), TopicExchangeName = ConfigManagerConf.GetValue("rabbitmq:TopicExchangeName"), RequestedConnectionTimeout = ConfigManagerConf.GetValue("rabbitmq:RequestedConnectionTimeout").ConvertToIntSafe(), SocketReadTimeout = ConfigManagerConf.GetValue("rabbitmq:SocketReadTimeout").ConvertToIntSafe(), SocketWriteTimeout = ConfigManagerConf.GetValue("rabbitmq:SocketWriteTimeout").ConvertToIntSafe(), Port = ConfigManagerConf.GetValue("rabbitmq:Port").ConvertToIntSafe(), }; }
public PublishQueueExecutor(RabbitMQOptions options) { if (options != null) { _rabbitMQOptions = options; return; } _rabbitMQOptions = new RabbitMQOptions { Password = ConfigManagerConf.GetValue("rabbitmq:Password"), UserName = ConfigManagerConf.GetValue("rabbitmq:UserName"), VirtualHost = ConfigManagerConf.GetValue("rabbitmq:VirtualHost"), TopicExchangeName = ConfigManagerConf.GetValue("rabbitmq:TopicExchangeName"), RequestedConnectionTimeout = ConfigManagerConf.GetValue("rabbitmq:RequestedConnectionTimeout").ConvertToIntSafe(), SocketReadTimeout = ConfigManagerConf.GetValue("rabbitmq:SocketReadTimeout").ConvertToIntSafe(), SocketWriteTimeout = ConfigManagerConf.GetValue("rabbitmq:SocketWriteTimeout").ConvertToIntSafe(), Port = ConfigManagerConf.GetValue("rabbitmq:Port").ConvertToIntSafe(), }; _hostNames = ConfigManagerConf.GetValue("rabbitmq:HostName").Split(','); }