您的位置:首页 > 其它

LindDotNetCore~Ocelot实现微服务网关

2018-01-31 16:40 387 查看
回到目录

网关在硬件里有自己的定义,而在软件架构里也有自己的解释,它就是所有请求的入口,请求打到网关上,经过处理和加工,再返回给客户端,这个处理过程中当然就是网关的核心,也是Ocelot的核心,我们可以把用户授权,校验,缓存,认证等很多关注点在网关中实现!

善友大哥收录的:http://www.csharpkit.com/2018-01-06_69695.html

原文地址:http://www.cnblogs.com/axzxs2001/p/8005041.html

Github地址:https://github.com/TomPallister/Ocelot

定义

API网关是一个服务器,是系统的唯一入口。从面向对象设计的角度看,它与外观模式类似。API网关封装了系统内部架构,为每个客户端提供一个定制的API。它可能还具有其它职责,如身份验证、监控、负载均衡、缓存、请求分片与管理、静态响应处理。

例如:手机和WEB网站都需要调用API接口,它们直接与网关进行通讯,而不用关心具体的服务是A还是B



项目Demo

安装Ocelot包:Install-Package Ocelot

建立两个项目,网关主项目,DemoA和DemoB,这样A和B两个项目都会指定网关项目,通过访问网关就可以访问这两个项目了.

Gateway网关项目,端口是5000

DemoA项目,端口是5001

DemoB项目,端口是5002

在Gateway项目添加配置文件configuration.json,将它复制到输出目录,右键-属性-始终复制

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/polly",
"DownstreamScheme": "http",
"DownstreamPort": 5001,
"DownstreamHost": "localhost",
"UpstreamPathTemplate": "/api/polly",
"UpstreamHttpMethod": [ "Get" ],
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 10,
"TimeoutValue": 5000
},
"HttpHandlerOptions": {
"AllowAutoRedirect": false,
"UseCookieContainer": false
},
"AuthenticationOptions": {
"AuthenticationProviderKey": "",
"AllowedScopes": []
}
}
]
}


现时在网关里配置子服务时,也支持路由规则,如控制器,Action时,如果你希望匹配以某个字符作为前缀的Restful标准的,可以通过下面代码进行配置

{
"DownstreamPathTemplate": "/api/{controller}",
"DownstreamScheme": "http",
"DownstreamPort": 5001,
"DownstreamHost": "localhost",
"UpstreamPathTemplate": "/api/{controller}",
"UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ],
},


在网关的启动时,把配置文件注入

public static IWebHost BuildWebHost(string[] args)
{
IWebHostBuilder builder = new WebHostBuilder();

//注入WebHostBuilder

return builder.ConfigureServices(service =>
{
service.AddSingleton(builder);
}).ConfigureAppConfiguration(conbuilder =>
{
conbuilder.AddJsonFile("configuration.json");
}).UseKestrel()
.UseUrls("http://*:5000")
.UseStartup<Startup>()
.Build();
}


添加ocelot的中间件和服务

services.AddOcelot(Configuration as ConfigurationRoot);

app.UseOcelot().Wait();


调试多个项目,这时我们的 5000和5001端口都会被监听,我们输入之间配置的api/polly路径,然后就可以看到它会自己绑定到5001这个子站上!



这样,我们的网关就算是跑起来了,所有项目有自己的路由模版,根据路由来查找服务!所有服务在外面看上去都像一个网站!

回到目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: