ASP.NET Core3.1 使用Ocelot 开源网关

1、搭建下游服务

添加2个ASP.NET Core项目,分别为Order.Api、User.Api

Order.Api端口设置为5001,User.Api端口设置为5002,均采用HTTP协议

UsersController代码:

[ApiController]
    [Route("v1")]
    public class UsersController : ControllerBase
    {
        private static List<UserItem> _users = new List<UserItem>
        {
            new UserItem("Mack"),
            new UserItem("Jack")
        };
        [HttpGet("users")]
        public IActionResult GetAll()
        {
            return Ok(_users);
        }
        [HttpGet("users/{id}")]
        public IActionResult Get(int id)
        {
            return Ok(_users.FirstOrDefault(_=>_.Id==id));
        }
    }
    public class UserItem
    {
        private static int _id=1001;
        public int Id { get; set; }
        public string Name { get; set; }
        public UserItem(string name)
        {
            Id= _id++;
            Name = name;
        }
    }

OrdersController代码:

[ApiController]
    [Route("v1")]
    public class OrdersController : ControllerBase
    {
        private static List<OrderItem> _orders = new List<OrderItem>()
        {
            new OrderItem(1001,99),
            new OrderItem(1001,199),
            new OrderItem(1002,59)
        };
        [HttpGet("orders")]
        public IActionResult GetAll()
        {
            return Ok(_orders);
        }
        [HttpGet("orders/{id}")]
        public IActionResult Get(int id)
        {
            return Ok(_orders.FirstOrDefault(_ => _.Id == id));
        }
        [HttpGet("users/{userId}/orders")]
        public IActionResult GetByUser(int userId)
        {
            return Ok(_orders.FirstOrDefault(_ => _.UserId == userId));
        }
    }
    public class OrderItem
    {
        private static int _id=10001;
        public int Id { get; set; }
        public DateTime CreationTime { get; set; }
        public int UserId { get; set; }
        public decimal Money { get; set; }
        public OrderItem(int userId,decimal money)
        {
            Id = _id++;
            CreationTime = DateTime.Now;
            UserId=userId;
            Money=money;
        }
    }

 

 

添加网关

新建一个项目,端口设置为5000

 

安装Nuget程序包:Ocelot,Core3.1使用15.0.7版本的Ocelot

添加ocelot.json文件

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamHttpMethod": [ "Get", "Post", "Delete", "Put", "Head" ],
      "UpstreamPathTemplate": "/order-api/{url}",
      // 设置优先级,越大越优先
      "Priority": 0
    },
    {
      "DownstreamPathTemplate": "/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "UpstreamHttpMethod": [ "Get", "Post", "Delete", "Put", "Head" ],
      "UpstreamPathTemplate": "/user-api/{url}"
    },
    {
      "DownstreamPathTemplate": "/v1/orders",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamHttpMethod": [ "Get" ],
      "UpstreamPathTemplate": "/order-api/v1/orders",
      "RateLimitOptions": {
        "EnableRateLimiting": true,
        "Period": "2s",
        "PeriodTimespan": 1,
        "Limit": 1
      },
      "Priority": 1,
      "Key": "All-Order"
    },
    // order和user的聚合  order
    {
      "DownstreamScheme": "http",
      "DownstreamPathTemplate": "/v1/users/{userId}/orders",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      "UpstreamHttpMethod": [ "Get" ],
      "UpstreamPathTemplate": "/order-api/v1/users/{userId}/orders",
      "Key": "Overview-Order"
    },
    {
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "DownstreamPathTemplate": "/v1/users/{userId}",
      "DownstreamScheme": "http",
      "UpstreamHttpMethod": [ "Get" ],
      "UpstreamPathTemplate": "/user-api/v1/users/{userId}",
      "Key": "Overview-User"
    },
    {
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "DownstreamPathTemplate": "/v1/users",
      "DownstreamScheme": "http",
      "UpstreamHttpMethod": [ "Get" ],
      "UpstreamPathTemplate": "/user-api/v1/users",
      "Key": "All-User"
    }

  ],
  // 聚合Api
  "Aggregates": [
    {
      "ReRouteKeys": [
        "Overview-User",
        "Overview-Order"
      ],
      "UpstreamPathTemplate": "/user-overview/{userId}"
    },
    {
      "ReRouteKeys": [
        "All-User",
        "All-Order"
      ],
      "UpstreamPathTemplate": "/all"
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5000"
  }
}

Program代码:

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.ConfigureAppConfiguration((context, config) =>
                    {
                        config.AddJsonFile("ocelot.json",false,true);
                    });
                    webBuilder.UseStartup<Startup>();
                });
    }

Startup代码:

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)
        {
            app.UseOcelot().Wait();
        }
    }

运行服务

把三个项目启动起来即可

 

posted @ 2022-07-16 22:37  码农小源  阅读(71)  评论(0编辑  收藏  举报