Ocelot是在.net core下网关的实现类库,通过Ocelot可以统一管理我们的webapi,不用再代码中调来调去的很多api地址,统一从网关调用就行了。
记录下如何简单的使用Ocelot
1.新建Gateway的网关项目,以及webapi的示例项目Service1和Service2
在Gateway项目中引用Ocelot类库通过nuget安装
2.Ocelot需要通过配置文件来实现请求的转发
建立ocelot.json配置文件
{
"ReRoutes": [
{
//Upstream表示上游请求,即客户端请求到API Gateway的请求
"UpstreamPathTemplate": "/Service1/{url}", //请求路径模板
"UpstreamHttpMethod": [ "Get", "Post" ], //请求方法数组
"UseServiceDiscovery": false, //启用服务发现
//Downstream表示下游请求,即API Gateway转发的目标服务地址
"DownstreamPathTemplate": "/api/{url}", //下游请求地址模板
"DownstreamScheme": "http", //请求协议,目前应该是支持http和https
//A***************指定单个转发地址
"DownstreamHostAndPorts": [ //请求服务地址
{
"Host": "localhost",
"Port": 7001
}
]
}
],
"GlobalConfiguration": {
//"ServiceDiscoveryProvider": {
// "Host": "127.0.0.1",
// "Port": 8500,
// "Type": "PollConsul"
//}
}
}
我们的目的是通过请求Gateway将请求转发到Service1的webapi上。
然后在Programe.cs是里修改CreateWebHostBuilder方法,指定读取ocelot.json配置文件,指定Gateway在7000端口
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext,builder)=> {
builder.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("ocelot.json", false, true);
})
.UseUrls("http://localhost:7000")
.UseStartup<Startup>();
3.在Startup.cs中注册服务
public class Startup {
// 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();//添加Ocelot服务
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseOcelot().Wait();//使用Ocelot服务
app.Run(async (context) => {
await context.Response.WriteAsync("Hello World!");
});
}
}
4.接下来对Service1的webapi示例项目中的programe.cs中指定7001端口运行
然后增加了一个webapi的控制器
namespace Service1.Controllers {
[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase {
[HttpGet]
public IActionResult GetById(string id) {
return Content($"This is Service1 id:{id}");
}
public IActionResult AddUser([FromBody] dynamic userDto) {
return Content($"Service1, User:{userDto.UserId},{userDto.Name}");
}
}
}
此时我们可以通过http://localhost:7001/api/Values/GetById?id=123进行访问会有内容输出
5.启动Gateway和Service1两个项目后
我们可以通过http://localhost:7000/Service1/Values/GetById?id=123进行访问了,此时我们是通过网关来进行请求转发的形式访问了。
关键是在上面的ocelot.json的配置文件中,
"DownstreamHostAndPorts": [ //请求服务地址
{
"Host": "localhost",
"Port": 7001
}
]
我们将请求转发到下游host:localhost,port:7001中了。
关于Ocelot标准的配置
{
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/",
"UpstreamHttpMethod": [
"Get"
],
"AddHeadersToRequest": {},
"AddClaimsToRequest": {},
"RouteClaimsRequirement": {},
"AddQueriesToRequest": {},
"RequestIdKey": "",
"FileCacheOptions": {
"TtlSeconds": 0,
"Region": ""
},
"ReRouteIsCaseSensitive": false,
"ServiceName": "",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 51876,
}
],
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 0,
"DurationOfBreak": 0,
"TimeoutValue": 0
},
"LoadBalancer": "",
"RateLimitOptions": {
"ClientWhitelist": [],
"EnableRateLimiting": false,
"Period": "",
"PeriodTimespan": 0,
"Limit": 0
},
"AuthenticationOptions": {
"AuthenticationProviderKey": "",
"AllowedScopes": []
},
"HttpHandlerOptions": {
"AllowAutoRedirect": true,
"UseCookieContainer": true,
"UseTracing": true
},
"UseServiceDiscovery": false
}
- Downstream是下游服务配置
- UpStream是上游服务配置
- Aggregates 服务聚合配置
- ServiceName, LoadBalancer, UseServiceDiscovery 配置服务发现
- AuthenticationOptions 配置服务认证
- RouteClaimsRequirement 配置Claims鉴权
- RateLimitOptions为限流配置
- FileCacheOptions 缓存配置
- QosOptions 服务质量与熔断
- DownstreamHeaderTransform头信息转发