一: consul 的 配置的有兩種方式,這里主要介紹 通過代碼 注冊服務(wù)
白水網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項目制作,到程序開發(fā),運營維護(hù)。創(chuàng)新互聯(lián)于2013年成立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)。Consul官網(wǎng):https://www.consul.io/
Consul的主要功能有服務(wù)注冊與發(fā)現(xiàn)、健康檢查、K-V存儲、多數(shù)據(jù)中心等。
consul.exe agent -dev
分別建3個項目 Api.Catalog,Api.Ordering,Provider.Consul
Api.Catalog和Api.Ordering 服務(wù)結(jié)構(gòu) 一樣,端口可以用不同
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Api.Catalog.Helper
{
public static class ConsulHelper
{
/// <summary> /// 服務(wù)注冊到consul
/// </summary> /// <param name="app"></param> /// <param name="lifetime"></param> public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime)
{
var consulClient = new ConsulClient(c =>
{
//consul地址 c.Address = new Uri(configuration["ConsulSetting:ConsulAddress"]);
});
var registration = new AgentServiceRegistration()
{
ID= Guid.NewGuid().ToString(),//服務(wù)實例唯一標(biāo)識 Name = configuration["ConsulSetting:ServiceName"],//服務(wù)名 Address = configuration["ConsulSetting:ServiceIP"], //服務(wù)IP Port = int.Parse(configuration["ConsulSetting:ServicePort"]),//服務(wù)端口 因為要運行多個實例,端口不能在appsettings.json里配置,在docker容器運行時傳入 Check = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter= TimeSpan.FromSeconds(5),//服務(wù)啟動多久后注冊 Interval = TimeSpan.FromSeconds(10),//健康檢查時間間隔 HTTP = $"http://{configuration["ConsulSetting:ServiceIP"]}:{configuration["ConsulSetting:ServicePort"]}{configuration["ConsulSetting:ServiceHealthCheck"]}",//健康檢查地址 Timeout = TimeSpan.FromSeconds(5)//等待時間 }
};
//服務(wù)注冊 consulClient.Agent.ServiceRegister(registration).Wait();
//應(yīng)用程序終止時,取消注冊 lifetime.ApplicationStopping.Register(() =>
{
consulClient.Agent.ServiceDeregister(registration.ID).Wait();
});
return app;
}
}
}
using Microsoft.AspNetCore.Mvc;
namespace Api.Catalog.Controllers
{
[Route("[controller]")]
[ApiController]
public class HealthCheckController : ControllerBase
{
/// <summary> /// 健康檢查接口
/// </summary> /// <returns></returns> [HttpGet]
public IActionResult Get() => Ok();
}
}
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace Api.Catalog.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "Api.Catalog1", "Api.Catalog2" };
}
[HttpGet("{id}")]
public string Get(int id)
{
return "Api.Catalog";
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConsulSetting": {
"ServiceName": "CatalogService",
"ServiceHealthCheck": "/healthcheck",
"ConsulAddress": "http://localhost:8500", //注意,docker容器內(nèi)部無法使用localhost訪問宿主機(jī)器,如果是控制臺啟動的話就用localhost "ServiceIP": "localhost",
"ServicePort": 52457
}
}
Startup.cs
using Api.Catalog.Helper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Api.Catalog
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration= configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c=>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api.Catalog", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c=> c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api.Catalog v1"));
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints=>
{
endpoints.MapControllers();
});
//服務(wù)注冊 app.RegisterConsul(Configuration, lifetime);
}
}
}
Provider.Consul 項目結(jié)構(gòu)
ocelot.json 配置
{
"GlobalConfiguration": {
//Ocelot應(yīng)用地址 "BaseUrl": "http://localhost:2808",
"ServiceDiscoveryProvider": {
//Consul地址 "Host": "http://localhost/",
//Consul端口 "Port": 8500,
"Type": "Consul" //由Consul提供服務(wù)發(fā)現(xiàn),每次請求Consul }
},
"Routes": [
{
"DownstreamPathTemplate": "/api/{everything}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 52457
},
{
"Host": "localhost",
"Port": 41097
}
],
"UpstreamPathTemplate": "/{everything}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
]
}
Program.cs 配置
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Provider.Consul
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(c=>
{
c.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder=>
{
webBuilder.UseStartup<Startup>();
});
}
}
Startup.cs 代碼
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Provider.Consul
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration= configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot().AddConsul();//注入Ocelot服務(wù) services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseOcelot();
app.UseAuthorization();
app.UseEndpoints(endpoints=>
{
endpoints.MapControllers();
});
}
}
}
運行后的效果
參考地址:https://www.cnblogs.com/xhznl/p/13091750.html
網(wǎng)站標(biāo)題:微服務(wù)Consul代碼dome-創(chuàng)新互聯(lián)
文章出自:http://jinyejixie.com/article32/deccsc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、外貿(mào)建站、自適應(yīng)網(wǎng)站、移動網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容