.netcore的微服务学习(二)--网关(gateway)之Ocelot学习

一,引用ocelot,本文测试16版本有BUG,只好使用15.0.7

.netcore的微服务学习(二)--网关(gateway)之Ocelot学习_第1张图片

 

 

二,startup的配置,很简单,就是注册和添加管道

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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 Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace OcelotDemo
{
    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();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ///使用coelot
            app.UseOcelot();
        }
    }
}

三,写配置文件,5001是我们控制台启动的端口,这个注意不要映射错

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001 //服务端口
        } //可以多个,自行负载均衡
      ],
      "UpstreamPathTemplate": "/OcelotDemo/{url}", //网关地址--url变量   //冲突的还可以加权重Priority
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ]
}

四,启动项目

.netcore的微服务学习(二)--网关(gateway)之Ocelot学习_第2张图片

 

 

dotnet OcelotDemo.dll urls="http://*:5003" --ip="120.0.0.1" --port=5003

五,访问http://localhost:5003/OcelotDemo/User/Get,这个可以拿到http://localhost:5001/api/User/Get地址的值,由于网关地址映射

 

你可能感兴趣的:(.netcore的微服务学习(二)--网关(gateway)之Ocelot学习)