简单微服务的搭建

简单微服务搭建

一、下载并启动Consul

访问www.consul.io下载最新版Consul,下载后命令行启动:

consul.exe agent -dev

consul默认端口是8500,打开localhost:8500就可以看到已经启动了Consul。

二、创建一个服务

应用注册到Consul,实现服务注册发现及健康检查。
1.引用Consul的nuget包,创建管道扩展,单例注入ConsulClient。

扩展方法:

    public static void UseConsul(this IApplicationBuilder app, IConfiguration configuration, IConsulClient consul)
    {
        string consulGroup = configuration["ConsulGroup"];//来自配置文件
        string ip = configuration["ip"];//来自命令行
        int port = Convert.ToInt32(configuration["port"]);//来自命令行
        string serviceId = $"{consulGroup}_{ip}_{port}";

        //健康检查
        var check = new AgentServiceCheck()
        {
            Interval = TimeSpan.FromSeconds(6),
            HTTP = $"http://{ip}:{port}/heartcheck",
            Timeout = TimeSpan.FromSeconds(2),
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(2)
        };

        //注册到consul
        var register = new AgentServiceRegistration()
        {
            Check = check,
            Address = ip,
            Port = port,
            Name = consulGroup,
            ID = serviceId
        };

        consul.Agent.ServiceRegister(register);
    }

Startup中添加扩展:

app.UseConsul(Configuration, consul);//consul来自方法注入IConsulClient

服务注入:

services.AddSingleton<IConsulClient>(x => new ConsulClient(c =>
{
      c.Address = new Uri("http://localhost:8500");
}));

三、创建网关

创建一个Gateway的WebApi项目,添加Nuget包--Ocelot(15.0.6版本)。
1.修改Startup文件
    public void ConfigureServices(IServiceCollection services)
        {
            //services.AddControllers();
            services.AddOcelot();
        }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //if (env.IsDevelopment())
        //{
        //    app.UseDeveloperExceptionPage();
        //}

        //app.UseRouting();

        //app.UseAuthorization();

        //app.UseEndpoints(endpoints =>
        //{
        //    endpoints.MapControllers();
        //});
        app.UseOcelot();
    }
2.添加一个gateway.json的配置文件
{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{url}", //下游地址,就是访问服务所需要的地址
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 7777 //服务端口
        }
      ],
      "UpstreamPathTemplate": "/{url}", //上游地址,就是访问网关的路由地址
      "UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ]
    }
  ]
}

修改Program.cs,调用json文件

public static IHostBuilder CreateHostBuilder(string[] args) =>
     Host.CreateDefaultBuilder(args)
     .ConfigureAppConfiguration((hostingContext, builder) =>
     {
          builder.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
          builder.AddJsonFile("gateway.json", false, true);
     })
     .ConfigureWebHostDefaults(webBuilder =>
     {
          webBuilder.UseStartup<Startup>();
     });

四、在网关中使用

在网关中添加nuget包--Ocelot.Provider.Consul(15.0.6版本)
1.修改gateway.json文件
{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{url}", //下游地址,就是访问服务所需要的地址
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/{url}", //上游地址,就是访问网关的路由地址
      "UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ],
      "ServiceName": "user_service",//consul的组名,需要与服务注册到consul时的名称相同
      "LoadBalancerOptions": {
        "Type": "RoundRobin"//轮询
      },
      "UseServiceDiscovery": true//启动服务发现
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:1000",//网关的url
    "ServiceDiscoveryProvider": {
      "Host": "localhost",//consul的ip
      "Port": "8500",//consul的port
      "Type": "Consul"
    }
  }
}
2.Startup文件中添加consul的服务
 	public void ConfigureServices(IServiceCollection services)
    {
        //services.AddControllers();
        services.AddOcelot().AddConsul();
    }

五、最终实现最简单的微服务的效果

1.先启动consul,再启动三个服务实例。

命令行启动三个User服务,端口分别是7777、8888、9999

dotnet MicroServiceLearn.UserService.dll --urls="http://*:{端口}" --ip="127.0.0.1" --port={端口}

此时,我们在consul的ui界面可以看到三个服务都已经注册到consul并通过了心跳检测。

2.启动网关项目
dotnet MicroServiceLearn.Gateway.dll --urls="http://*:1000" --ip="127.0.0.1" --port=1000

最终效果展示:

posted @ 2020-09-22 08:51  aaayi  阅读(652)  评论(2编辑  收藏  举报