asp.net core微服务架构介绍

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)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值