Fork me on GitHub

Ocelot网关

Ocelot是一个.net core框架下的网关的开源项目,下图是官方给出的基础实现图,即把后台的多个服务统一到网关处,前端应用:桌面端,web端,app端都只用访问网关即可。

 

Ocelot的实现原理就是把客户端对网关的请求(Request),按照configuration.json的映射配置,转发给对应的后端http service,然后从后端http service获取响应(Response)后,再返回给客户端。当然有了网关后,我们可以在网关这层去做统一验证,也可以在网关处统一作监控。

接下来做个Demo

新建三个asp.net core web aip项目:

OcelotGateway网关项目,端口是5000

DemoAAPI项目A,端口是5001

DemoBAPI项目B,端口是5002

(注:端口可以在每个项目的Properties下的launchSettings.json中修改,发布后的端口可以在Program.cs中用UseUrls(“http://*:5000”)来修改)

对于OcelotGateway:

引用Ocelot的Nuget包:

视图->其他窗口->程序包管理控制台:Install-Package Ocelot

或项目右键“管理Nuget程序包”,在浏览里查找Ocelot进行安装

在OcelotGateway项目中添加一个configuration.json文件,关把它的属性“复制到输出目录”,设成“始终复制”,内容如下:

{

  "ReRoutes": [

    {

      "DownstreamPathTemplate": "/demoaapi/values",

      "DownstreamScheme": "http",

      "DownstreamPort": 5001,

      "DownstreamHost": "localhost",

      "UpstreamPathTemplate": "/demoaapi/values",

      "UpstreamHttpMethod": [ "Get" ],

      "QoSOptions": {

        "ExceptionsAllowedBeforeBreaking": 3,

        "DurationOfBreak": 10,

        "TimeoutValue": 5000

      },

      "HttpHandlerOptions": {

        "AllowAutoRedirect": false,

        "UseCookieContainer": false

      },

      "AuthenticationOptions": {

        "AuthenticationProviderKey": "",

        "AllowedScopes": []

      }

    },

    {

      "DownstreamPathTemplate": "/demobapi/values",

      "DownstreamScheme": "http",

      "DownstreamPort": 5002,

      "DownstreamHost": "localhost",

      "UpstreamPathTemplate": "/demobapi/values",

      "UpstreamHttpMethod": [ "Get" ],

      "QoSOptions": {

        "ExceptionsAllowedBeforeBreaking": 3,

        "DurationOfBreak": 10,

        "TimeoutValue": 5000

      },

      "HttpHandlerOptions": {

        "AllowAutoRedirect": false,

        "UseCookieContainer": false

      },

      "AuthenticationOptions": {

        "AuthenticationProviderKey": "",

        "AllowedScopes": []

      }

    }

  ]

}

接下来对OcelotGateway的Program.cs进行改造 

 1 using Microsoft.AspNetCore.Hosting;
 2 
 3 using Microsoft.Extensions.Configuration;
 4 
 5 using Microsoft.Extensions.DependencyInjection;
 6 
 7  
 8 
 9 namespace OcelotGateway
10 
11 {
12 
13     public class Program
14 
15     {
16 
17         public static void Main(string[] args)
18 
19         {
20 
21             BuildWebHost(args).Run();
22 
23         }
24 
25         public static IWebHost BuildWebHost(string[] args)
26 
27         {
28 
29             IWebHostBuilder builder = new WebHostBuilder();
30 
31             //注入WebHostBuilder
32 
33             return builder.ConfigureServices(service =>
34 
35                 {
36 
37                     service.AddSingleton(builder);
38 
39                 })
40 
41                 //加载configuration配置文人年
42 
43                 .ConfigureAppConfiguration(conbuilder =>
44 
45                 {
46 
47                     conbuilder.AddJsonFile("configuration.json");
48 
49                 })
50 
51                 .UseKestrel()
52 
53                 .UseUrls("http://*:5000")
54 
55                 .UseStartup<Startup>()
56 
57                 .Build();
58 
59         }
60 
61     }
62 
63 }
View Code

同时,修改Startup.cs

 1 using Microsoft.AspNetCore.Builder;
 2 
 3 using Microsoft.AspNetCore.Hosting;
 4 
 5 using Microsoft.Extensions.Configuration;
 6 
 7 using Microsoft.Extensions.DependencyInjection;
 8 
 9 using Ocelot.DependencyInjection;
10 
11 using Ocelot.Middleware;
12 
13  
14 
15 namespace OcelotGateway
16 
17 {
18 
19     public class Startup
20 
21     {
22 
23         public Startup(IConfiguration configuration)
24 
25         {
26 
27             Configuration = configuration;
28 
29         }
30 
31         public IConfiguration Configuration { get; }     
32 
33         public void ConfigureServices(IServiceCollection services)
34 
35         {      
36 
37             //注入配置文件,AddOcelot要求参数是IConfigurationRoot类型,所以要作个转换
38 
39             services.AddOcelot(Configuration as ConfigurationRoot);
40 
41         }
42 
43         public  void Configure(IApplicationBuilder app, IHostingEnvironment env)
44 
45         {
46 
47             //添加中间件
48 
49             app.UseOcelot().Wait();
50 
51         }
52 
53     }
54 
55 }
View Code

为了测试数据好看,我们把DemoAAPI项目和DemoBAPI项目的ValuesController作一下修改:    

 1 [Route("demoaapi/[controller]")]
 2 
 3     public class ValuesController : Controller
 4 
 5     {       
 6 
 7         [HttpGet]
 8 
 9         public IEnumerable<string> Get()
10 
11         {
12 
13             return new string[] { "DemoA服务", "请求" };
14 
15         }
16 
17 //……
18 
19 }
20 
21  
22 
23     [Route("demobapi/[controller]")]
24 
25     public class ValuesController : Controller
26 
27     {       
28 
29         [HttpGet]
30 
31         public IEnumerable<string> Get()
32 
33         {
34 
35             return new string[] { "DemoB服务", "请求" };
36 
37         }
38 
39 //……
40 
41 }
View Code

最后在解决方案属性->多个启动项目中,把DemoAAPI,DemoBAPI,OcelotGateway都设成启动,开始启动解决方案,效果如下图 

 

《基于.net core微服务架构视频》

 http://edu.51cto.com/course/13342.html

posted @ 2017-12-08 13:51  桂素伟  阅读(4870)  评论(18编辑  收藏  举报