elot,掌握一个基础项目应用,学习起来也更直观。示例有三个项目:一个是网关APIGateway项目,有二个是web api服务。 项目实现的功能是:客户端统一通过网关作为入口点访问,实现路由的功能。github开源地址 架构如下图所示:
2.1 CustomersAPIServices项目
该项目是一个web api项目,用来处理客户事务的API服务。该地址为http://localhost:9001, 可以在“项目选项”中指定url,也可以在Host启动时配置。
(1) Program类添加UseUrls
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>().UseUrls("http://*:9001");
(2) 在CustimersAPIServices项目中创建一个CustomersController
[Route("api/[controller]")]
public class CustomersController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "Catcher Wong", "James Li" };
}
[HttpGet("{id}")]
public string Get(int id)
{
return $"Catcher Wong - {id}";
}
}
2.2 ProductsAPIServices项目
该项目是一个web api项目,处理产品某事的API服务。该地址为http://localhost:9002, 可以在“项目选项”中指定url,也可以在Host启动时配置。
(1) Program类添加UseUrls
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>().UseUrls("http://*:9002");
(2) 在ProductsAPIServices项目中创建ProductsController
[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "Surface Book 2", "Mac Book Pro" };
}
}
2.3 APIGateway项目
该项目是Ocelot网关项目,先安装Ocelot包。在项目中添加一个Ocelot的json配置文件,这里创建的是configuration.json文件。
(1) configuration.json(配置Ocelot)
{
//ReRoutes:处理上游请求的对象(客户端),每个数组{} 就是配置:上游地址和对应下游地址
"ReRoutes": [
{
//以Downstream开头的,是要转发到下游服务器的地址(CustomersAPIServices),与nginx转发类似
//下面所有Downstream开头的,组成一个转发url,转发地址是http://localhost:9001/api/customers
"DownstreamPathTemplate": "/api/customers",
"DownstreamScheme": "http",
// "DownstreamHost": "localhost",
// "DownstreamPort": 9001,
//转发到下游服务器的主机和端口。
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9001
}
],
//Upstream开头是指上游服务器(客户端)访问地址,通过http get方式访问。
//也就是说客户端访问http://localhost:9000/customers 实际是转发到了http://localhost:9001/api/customers的服务
"UpstreamPathTemplate": "/customers",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/customers/{id}",
"DownstreamScheme": "http",
// "DownstreamHost": "localhost",
// "DownstreamPort": 9001,
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9001
}
],
"UpstreamPathTemplate": "/customers/{id}",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/products",
"DownstreamScheme": "http",
// "DownstreamPort": 9002,
// "DownstreamHost": "localhost",
"DownstreamHostAndPorts": [
{
"Host&q