// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute("areaRoute", "view/{area:exists}/{controller}/{action=Index}/{id?}"); routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute("spa-fallback", new { controller = "Home", action = "Index" }); }); ConsulService consulService = new ConsulService() { IP = Configuration["Consul:IP"], Port = Convert.ToInt32(Configuration["Consul:Port"]) }; HealthService healthService = new HealthService() { IP = Configuration["Service:IP"], Port = Convert.ToInt32(Configuration["Service:Port"]), Name = Configuration["Service:Name"], }; app.RegisterConsul(lifetime, healthService, consulService); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); Settings.AuthorizationKey = Configuration.GetSection("ApplicationSettings:AuthorizationKey")?.Value; // Add Application Insights services into service collection services.AddApplicationInsightsTelemetry(); // Add the standard telemetry client services.AddSingleton <IBotTelemetryClient, BotTelemetryClient>(); // Add ASP middleware to store the HTTP body, mapped with bot activity key, in the httpcontext.items // This will be picked by the TelemetryBotIdInitializer services.AddTransient <TelemetrySaveBodyASPMiddleware>(); // Add telemetry initializer that will set the correlation context for all telemetry items services.AddSingleton <ITelemetryInitializer, OperationCorrelationTelemetryInitializer>(); // Add telemetry initializer that sets the user ID and session ID (in addition to other // bot-specific properties, such as activity ID) services.AddSingleton <ITelemetryInitializer, TelemetryBotIdInitializer>(); // Create the telemetry middleware to track conversation events services.AddSingleton <IMiddleware, TelemetryLoggerMiddleware>(); var apps = new List <LuisAppRegistration>(); Configuration.GetSection("LuisAppRegistrations").Bind(apps); Settings.LuisAppRegistrations = apps; // Adding Consul hosted service using (ConsulService consulService = new ConsulService(EnvironmentName, ContentRootPath)) { consulService.Initialize(services, Configuration); } services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "https://BotApp.Luis.Router.Identity", ValidAudience = "https://BotApp.Luis.Router.Identity", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.AuthorizationKey)) }; }); services.AddCors(o => o.AddPolicy("AllowAllPolicy", options => { options.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); }
/// <summary> /// 从Consul加载集群成员 /// </summary> public override List <Member> GetMembers(string clusterName) { var memberKey = string.Format("Swift/{0}/Members", clusterName); KVPair memberKV = ConsulKV.Get(memberKey); if (memberKV == null) { memberKV = ConsulKV.Create(memberKey); } var configMemberList = new List <MemberWrapper>(); if (memberKV.Value != null) { configMemberList = JsonConvert.DeserializeObject <List <MemberWrapper> >(Encoding.UTF8.GetString(memberKV.Value)); } var serviceName = string.Format("Swift-{0}-Member", clusterName); var healths = ConsulService.GetHealths(serviceName); List <MemberWrapper> needRemoveList = new List <MemberWrapper>(); foreach (var configMember in configMemberList) { var serviceId = string.Format("Swift-{0}-Member-{1}", clusterName, configMember.Id); healths.TryGetValue(serviceId, out bool isHealth); configMember.Status = isHealth ? 1 : 0; } return(configMemberList.Select(d => d.ConvertToBase()).ToList()); }
/// <summary> /// 注册这个服务到Consul里 /// </summary> private async void RegisterService() { try { //下面的内容可以放在一个配置文件里,然后转换json为对象 _consulService = new ConsulService(); _consulService.Id = "identity01"; _consulService.Name = "identity"; _consulService.Tags = new List <string> { "identity01" }; _consulService.Address = "127.0.0.1"; _consulService.Port = 5000; _consulService.Enable_Tag_Override = false; _consulService.checks = new List <ConsulServiceCheck> { new ConsulServiceCheck() { Name = "identitycheck", Http = "http://127.0.0.1:5000/health", Tls_Skip_Verify = true, Method = "GET", Interval = "5s", Timeout = "30s", } }; HttpClient client = new HttpClient(); var response = await client.PutAsJsonAsync <ConsulService>("http://127.0.0.1:8500/v1/agent/service/register", _consulService); statusCode = response.StatusCode.ToString(); } catch (Exception e) { } }
private async void OnApplicationStopping() { using (ConsulService consulService = new ConsulService(EnvironmentName, ContentRootPath)) { await consulService.Stop(); } }
/// <summary> /// 注册这个服务到Consul里 /// </summary> private async void RegisterService() { _consulService = new ConsulService(); _consulService.Id = "user02"; _consulService.Name = "user"; _consulService.Tags = new List <string> { "user02" }; _consulService.Address = "127.0.0.1"; _consulService.Port = 8889; _consulService.Enable_Tag_Override = false; _consulService.checks = new List <ConsulServiceCheck> { new ConsulServiceCheck() { Name = "user02check", Http = "http://127.0.0.1:8889/health", Tls_Skip_Verify = true, Method = "GET", Interval = "5s", Timeout = "30s", } }; HttpClient client = new HttpClient(); var response = await client.PutAsJsonAsync <ConsulService>("http://127.0.0.1:8500/v1/agent/service/register", _consulService); statusCode = response.StatusCode.ToString(); }
public GrpcService(ILogger <GrpcService> logger, IConfiguration config, ConsulService consulSrv) { _logger = logger; _config = config; _consulSrv = consulSrv; _grpcTimeout = _config.GetValue <int>("GrpcTimeout"); }
public GetServiceResponse(ConsulService response) { Id = response.Id; Name = response.Name; Address = response.Address; Tags = response.Tags; Version = response.Version; }
public GetServiceResponse(ConsulService response) { Id = response.Id; Name = response.Name; Address = response.Address; Tags = response.Tags; Version = response.Version; }
public RunConsulScheduledTasks(IHttpClientFactory httpClientFactory, IOptions <ConsulService> consulService, IOptions <HealthSetting> healthSetting, IHostApplicationLifetime lifetime) { _consulService = consulService?.Value; _healthSetting = healthSetting?.Value; _client = httpClientFactory.CreateClient(); _client.Timeout = TimeSpan.FromSeconds(100000); _client.DefaultRequestVersion = new Version(1, 0); _client.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact; _lifetime = lifetime; }
public static IApplicationBuilder ConsulRegister(this IApplicationBuilder app) { //design ConsulService class as long-lived or store ApplicationServices instead Service = app.ApplicationServices.GetService <ConsulService>(); var life = app.ApplicationServices.GetService <IApplicationLifetime>(); life.ApplicationStarted.Register(OnStarted); life.ApplicationStopping.Register(OnStopping); return(app); }
public IActionResult Test() { string content = "Order调用Auth和Product"; var consulService = new ConsulService(_configuration); content += consulService.GetAsync("AuthService", "test/index").Result; content += consulService.GetAsync("ProductService", "home/test").Result; return(Content(content)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); Settings.AuthorizationKey = Configuration.GetSection("ApplicationSettings:AuthorizationKey")?.Value; Settings.KeyVaultEncryptionKey = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value; Settings.KeyVaultApplicationCode = Configuration.GetSection("ApplicationSettings:KeyVaultApplicationCode")?.Value; // Add Application Insights services into service collection services.AddApplicationInsightsTelemetry(); // Add the standard telemetry client services.AddSingleton <TelemetryClient, TelemetryClient>(); // Adding KeyVault service services.AddSingleton <IKeyVaultService>(sp => { return(new KeyVaultService(EnvironmentName, ContentRootPath)); }); KeyVaultService keyVaultService = new KeyVaultService(EnvironmentName, ContentRootPath); EncryptionKey = keyVaultService.GetVaultKeyAsync(Settings.KeyVaultEncryptionKey).Result; ApplicationCode = keyVaultService.GetVaultKeyAsync(Settings.KeyVaultApplicationCode).Result; // Adding Consul hosted service using (ConsulService consulService = new ConsulService(EnvironmentName, ContentRootPath)) { consulService.Initialize(services, Configuration); } services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "https://BotApp.Luis.Router.Identity", ValidAudience = "https://BotApp.Luis.Router.Identity", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Settings.AuthorizationKey)) }; }); services.AddCors(o => o.AddPolicy("AllowAllPolicy", options => { options.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); })); }
public void GetConfigurationTest() { // arrage // act ConsulService consulService = new ConsulService(EnvironmentName, ContentRootPath); ConsulConfig config = consulService.GetConfiguration(); // assert Assert.Equal(configuration.Address, config.Address); Assert.Equal(configuration.ServiceName, config.ServiceName); Assert.Equal(configuration.ServiceID, config.ServiceID); Assert.Equal(configuration.ServiceTag, config.ServiceTag); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseStaticFiles(); #region 使用HttpContext app.UseStaticHttpContext(); #endregion app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); #region register this service ConsulService consulService = new ConsulService() { IP = Configuration["Consul:IP"], Port = Convert.ToInt32(Configuration["Consul:Port"]) }; HealthService healthService = new HealthService() { IP = Configuration["Service:IP"], Port = Convert.ToInt32(Configuration["Service:Port"]), Name = Configuration["Service:Name"], }; //app.RegisterConsul(lifetime, healthService, consulService); #endregion }
/// <summary> /// 注册配置 /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// /// <param name="lifeTime"></param> // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifeTime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseStaticFiles(); //app.UseApiVersioning(); // exceptionless //ExceptionlessClient.Default.Configuration.ApiKey = Configuration["Exceptionless:ApiKey"]; //ExceptionlessClient.Default.Configuration.ServerUrl = Configuration["Exceptionless:ServerUrl"]; ExceptionlessClient.Default.SubmittingEvent += OnSubmittingEvent; app.UseExceptionless(_configuration); // swagger app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); }); ConsulService consulService = new ConsulService() { IP = _configuration["Consul:IP"], Port = Convert.ToInt32(_configuration["Consul:Port"]) }; HealthService healthService = new HealthService() { IP = _configuration["Service:IP"], Port = Convert.ToInt32(_configuration["Service:Port"]), Name = _configuration["Service:Name"], }; //app.RegisterConsul(lifeTime, healthService, consulService); }
/// <summary> /// 注册这个服务到Consul里 /// </summary> private async void RegisterService() { try { _consulService = new ConsulService(); _consulService.Id = "contact01"; _consulService.Name = "contacts"; _consulService.Tags = new List <string> { "contact01" }; _consulService.Address = "127.0.0.1"; _consulService.Port = 8008; _consulService.Enable_Tag_Override = false; _consulService.checks = new List <ConsulServiceCheck> { new ConsulServiceCheck() { Name = "contact01check", Http = "http://127.0.0.1:8008/health", Tls_Skip_Verify = true, Method = "GET", Interval = "5s", Timeout = "30s", } }; using (HttpClient client = new HttpClient()) { var response = await client.PutAsJsonAsync <ConsulService>("http://127.0.0.1:8500/v1/agent/service/register", _consulService); statusCode = response.StatusCode.ToString(); } } catch (Exception e) { ////把异常添加到队列进行日志打印,使用Guid是防止键名重复 //LogDic.Add(Guid.NewGuid() + "error", e.Message + "\n\r" + e.StackTrace); } }
public static void UseVault(this IServiceCollection services, string[] key) { services.AddDefaultServices(); IServiceProvider provider = services.BuildServiceProvider(); var loggerFactory = LoggerFactory.Create(builder => { builder .AddConsole() .AddDebug(); }); ILogger <ConsulService> logger = loggerFactory.CreateLogger <ConsulService>(); IConfiguration configuration = provider.GetRequiredService <IConfiguration>(); IHttpClientFactory httpClientFactory = provider.GetRequiredService <IHttpClientFactory>(); var service = new ConsulService(logger, httpClientFactory, configuration); List <Consul> list = new List <Consul>(); var db = provider.GetRequiredService <consulService.Memory.Config>(); foreach (var item in key) { var load = db.Get(item); if (load == null || (load.validUntil < DateTime.Now)) { var save = service.GetFromConsul(item).Result; if (save != null) { db.Set(save); } } } }
public async Task <IActionResult> TestPostAsync() { string content = "Order调用Post \n"; var consulService = new ConsulService(_configuration); var user = new User() { Name = "123", Age = "456" }; content += consulService.PostAsync("ProductService", "home/add", JsonConvert.SerializeObject(new { a = "aaa", b = "bbb" })).Result; content += "\n"; content += consulService.PostAsync("ProductService", "home/new", JsonConvert.SerializeObject(user)).Result; using (System.Net.Http.HttpClient http = new HttpClient()) { using var HttpContent = new StringContent(JsonConvert.SerializeObject(user), System.Text.Encoding.UTF8, "application/json"); var ss = http.PostAsync($"http://localhost:10100/home/new", HttpContent); var result = ss.Result.Content; content += await result.ReadAsStringAsync(); } return(Content(content)); }
public void InitializeTest() { // arrage var builder = new ConfigurationBuilder() .SetBasePath(ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); var configuration = builder.Build(); IServiceCollection services = new ServiceCollection(); // act ConsulService consulService = new ConsulService(EnvironmentName, ContentRootPath); consulService.Initialize(services, configuration); IServiceProvider serviceProvider = services.BuildServiceProvider(); IConsulClient service = serviceProvider.GetRequiredService <IConsulClient>(); // assert Assert.NotNull(service); }
public GrpcModel(ConsulService consulSrv, GrpcService grpcSrv) { _consulSrv = consulSrv; _grpcSrv = grpcSrv; }
// 服务注册 public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, HealthService healthService, ConsulService consulService) { //var server = AppConfiguration.Configurations["urls"]; var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{consulService.IP}:{consulService.Port}"));//请求注册的 Consul 地址 var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), //服务启动多久后注册 Interval = TimeSpan.FromSeconds(10), //健康检查时间间隔,或者称为心跳间隔 HTTP = $"http://{healthService.IP}:{healthService.Port}/api/health", //健康检查地址 Timeout = TimeSpan.FromSeconds(5) }; // Register service with consul var registration = new AgentServiceRegistration() { Checks = new[] { httpCheck }, ID = healthService.Name + "_" + healthService.Port, Name = healthService.Name, Address = healthService.IP, Port = healthService.Port, Tags = new[] { $"urlprefix-/{healthService.Name}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别 }; consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起) lifetime.ApplicationStopping.Register(() => { consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册 }); return(app); }
public ConsulSetModel(ConsulService consulSrv, IConfiguration config) { _consulSrv = consulSrv; _config = config; }
public UnregisterModel(ConsulService consulSrv) { _consulSrv = consulSrv; }
public IndexModel(ConsulService consulSrv) { _consulSrv = consulSrv; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Reading settings Settings.MicrosoftAppId = Configuration.GetSection("ApplicationSettings:MicrosoftAppId")?.Value; Settings.MicrosoftAppPassword = Configuration.GetSection("ApplicationSettings:MicrosoftAppPassword")?.Value; Settings.BotConversationStorageConnectionString = Configuration.GetSection("ApplicationSettings:BotConversationStorageConnectionString")?.Value; Settings.BotConversationStorageKey = Configuration.GetSection("ApplicationSettings:BotConversationStorageKey")?.Value; Settings.BotConversationStorageDatabaseId = Configuration.GetSection("ApplicationSettings:BotConversationStorageDatabaseId")?.Value; Settings.BotConversationStorageUserCollection = Configuration.GetSection("ApplicationSettings:BotConversationStorageUserCollection")?.Value; Settings.BotConversationStorageConversationCollection = Configuration.GetSection("ApplicationSettings:BotConversationStorageConversationCollection")?.Value; Settings.KeyVaultEncryptionKey = Configuration.GetSection("ApplicationSettings:KeyVaultEncryptionKey")?.Value; Settings.KeyVaultApplicationCode = Configuration.GetSection("ApplicationSettings:KeyVaultApplicationCode")?.Value; // Adding CosmosDB user storage CosmosDbStorage userstorage = new CosmosDbStorage(new CosmosDbStorageOptions { AuthKey = Settings.BotConversationStorageKey, CollectionId = Settings.BotConversationStorageUserCollection, CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString), DatabaseId = Settings.BotConversationStorageDatabaseId, }); var userState = new UserState(userstorage); services.AddSingleton(userState); // Adding CosmosDB conversation storage CosmosDbStorage conversationstorage = new CosmosDbStorage(new CosmosDbStorageOptions { AuthKey = Settings.BotConversationStorageKey, CollectionId = Settings.BotConversationStorageConversationCollection, CosmosDBEndpoint = new Uri(Settings.BotConversationStorageConnectionString), DatabaseId = Settings.BotConversationStorageDatabaseId, }); var conversationState = new ConversationState(conversationstorage); services.AddSingleton(conversationState); // Adding Consul hosted service using (ConsulService consulService = new ConsulService(EnvironmentName, ContentRootPath)) { consulService.Initialize(services, Configuration); } // Adding MVC compatibility services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Adding the credential provider to be used with the Bot Framework Adapter services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>(); // Adding the channel provider to be used with the Bot Framework Adapter services.AddSingleton <IChannelProvider, ConfigurationChannelProvider>(); // Adding the Bot Framework Adapter with error handling enabled services.AddSingleton <IBotFrameworkHttpAdapter, AdapterWithErrorHandler>(); // Adding middlewares services.AddSingleton(new AutoSaveStateMiddleware(userState, conversationState)); services.AddSingleton(new ShowTypingMiddleware()); // Adding telemetry ConfigureTelemetry(services); // Adding HttpClient and HttpClientHandler var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; var httpClient = new HttpClient(handler); // Adding LUIS Router service services.AddSingleton <ILuisRouterService>(sp => { return(new LuisRouterService(httpClient, EnvironmentName, ContentRootPath, userState, sp.GetRequiredService <IBotTelemetryClient>())); }); // Adding QnAMaker Router service services.AddSingleton <IQnAMakerService>(sp => { return(new QnAMakerService(httpClient, EnvironmentName, ContentRootPath, sp.GetRequiredService <IBotTelemetryClient>())); }); // Adding WebChat service services.AddSingleton <IWebChatService>(sp => { return(new WebChatService(httpClient, EnvironmentName, ContentRootPath)); }); // Adding KeyVault service services.AddSingleton <IKeyVaultService>(sp => { return(new KeyVaultService(EnvironmentName, ContentRootPath)); }); KeyVaultService keyVaultService = new KeyVaultService(EnvironmentName, ContentRootPath); EncryptionKey = keyVaultService.GetVaultKeyAsync(Settings.KeyVaultEncryptionKey).Result; ApplicationCode = keyVaultService.GetVaultKeyAsync(Settings.KeyVaultApplicationCode).Result; // Adding Active Directory service services.AddSingleton <IActiveDirectoryService>(sp => { return(new ActiveDirectoryService(EnvironmentName, ContentRootPath)); }); // Adding accessor services.AddSingleton(sp => { // We need to grab the conversationState we added on the options in the previous step var options = sp.GetRequiredService <IOptions <BotFrameworkOptions> >().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors"); } // Create the custom state accessor. // State accessor enable other components to read and write individual properties of state. var accessor = new BotAccessor(loggerFactory, conversationState, userState) { ConversationDialogState = conversationState.CreateProperty <DialogState>("DialogState"), AskForExamplePreference = conversationState.CreateProperty <bool>("AskForExamplePreference"), IsAuthenticatedPreference = userState.CreateProperty <bool>("IsAuthenticatedPreference") }; return(accessor); }); // Adding the bot as a transient. In this case the ASP Controller is expecting an IBot services.AddTransient <IBot, BotAppBot>(); }