.net core

.net core 微服务之API网关 开源中间件 Oce

2018-09-02  本文已影响32人  潇潇剑_易水阁

一夫当关万夫莫开

一:源起:

二:搬砖:
此处流程只是Ocelot作为网关转发请求的简单demo,代码设置源自网上,部分自己瞎改

环境:

Ocelot配置文件

{
  "ReRoutes": [
    //微服务一配置:
    {
      "DownstreamPathTemplate": "/api/get",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 60001
        }
      ],
      "UpstreamPathTemplate": "/api/get",
      "UpstreamHttpMethod": [ "Get" ]
    },
    //微服务二配置:
    {
      "DownstreamPathTemplate": "/api/post",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 60002
        }
      ],
      "UpstreamPathTemplate": "/api/post",
      "UpstreamHttpMethod": [ "Get" ]
    }


  ],
  "GlobalConfiguration": {
    "BaseUrl": "localhost:60000"
  }
}

网关api设置:
在 Program.cs添加Ocelot的配置文件

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)


             //此处添加Ocelot的配置
             .ConfigureAppConfiguration((hostingContext, builder) => {
                 builder
                 .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                 .AddJsonFile("ocelot.json");
             })


                .UseStartup<Startup>()
                .Build();

在Startup.cs添加Ocelot服务

 public void ConfigureServices(IServiceCollection services)
        {
            //添加网关配置
            services.AddOcelot(Configuration);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
         
            app.UseOcelot().Wait();
        }

2个微服务就是普通的设置:

namespace MicroServicePost.Controllers
{
    [Route("api/[controller]")]
    public class PostController : Controller
    {
        [HttpGet]
        public IEnumerable<string> yishuiPost()
        {
            return new string[] { "易", "水", "POST" };
        }
    }
}

运行结果如下:

当往网关输入对应的微服务路由时,你能看到不同服务的回调,当然实际上微服务端口还是需要禁止访问的,对外面只是暴露80端口这个就是后话了。

上一篇 下一篇

猜你喜欢

热点阅读