consul是独立的程序,直接运行
官网https://www.consul.io
consul.exe agent -dev -node=127.0.0.1
运行起来后:
写个Service(这里的就是webapi),要安装consul包
为了方便使用,改Program.cs,可命令行参数指定启动url
public static IHostBuilder CreateHostBuilder(string[] args)
{
var config = new ConfigurationBuilder().AddCommandLine(args).Build();
var ip = config["ip"];
var port = config["port"];
return Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseUrls($"http://{ip}:{port}");
});
}
让Service启动时向consul注册,退出后向consul注销:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//services.AddMvc();
services.AddMvc(options => { options.EnableEndpointRouting = false; });
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Microsoft.AspNetCore.Hosting.IApplicationLifetime appLifeTime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Msg Service");
});
});
app.UseMvc();
var ip = Configuration["ip"];
var port = Configuration["port"];
var serviceName = "MsgService";
var serviceId = serviceName + Guid.NewGuid();
using (var consulClient=new ConsulClient(ConsulClientConfig))
{
consulClient.Agent.ServiceRegister(new AgentServiceRegistration()
{
Address = ip,
Port = int.Parse(port),
ID = serviceId,
Name = serviceName,
Check = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
HTTP=$"http://{ip}:{port}/api/Health",
Interval=TimeSpan.FromSeconds(10),
Timeout=TimeSpan.FromSeconds(5)
},
}).Wait();
}
appLifeTime.ApplicationStopped.Register(()=> {
using (var consulClient = new ConsulClient(ConsulClientConfig)) {
Console.WriteLine("--ApplicationStopped,ServiceDeregister");
consulClient.Agent.ServiceDeregister(serviceId).Wait();
}
});
}
private void ConsulClientConfig(ConsulClientConfiguration c) {
c.Address = new Uri("http://127.0.0.1:8500");
c.Datacenter = "dc1";
}
}
运行Service的2个实例:
consul面板效果:
然后再写个webapi当作网关:
安装Ocelot包,
和Consul不同,Ocelot不是一个单独的程序,需要和自己写的程序结合使用:
Ocelot需要一个配置文件:xxx.json
可以配置成直接访问自己写的service实例地址,
但是一般是配置成去访问consul服务中心地址:
{
"Routes": [
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
//"DownstreamHostAndPorts": [
// {
// "Host": "localhost",
// "Port": 6001
// }
//],
"UpstreamPathTemplate": "/MsgService/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"ServiceName": "MsgService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
//,"UseServiceDiscovery": true
}
],
"GlobalConfiguration": {
//"BaseUrl": "https://localhost:5000",
"ServiceDiscoveryProvider": {
"Scheme": "http",
"Host": "127.0.0.1",
"Port": 8500,
"Type": "Consul"
}
}
}
让写的网关程序使用上这个配置文件:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().ConfigureAppConfiguration((host, builder) =>
{
builder.AddJsonFile("configuration.json", false, true);
});
});
}
让写的网关程序使用Ocelot中间件:
public class Startup
{
//public IConfiguration Configuration { get; }
//public Startup(IConfiguration configuration)
//{
// Configuration = configuration;
//}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//services.AddOcelot(Configuration).AddConsul();
//services.AddOcelot();
services.AddOcelot().AddConsul();
}
// 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.UseEndpoints(endpoints =>
//{
// endpoints.MapGet("/", async context =>
// {
// await context.Response.WriteAsync("Hello World!");
// });
//});
app.UseOcelot().Wait();
}
}
启动网关程序:
通过网关来访问写的service(网关--->consul--->service)