官方文档:http://ocelot.readthedocs.io/en/latest/introduction/gettingstarted.html
新建两个Asp.net core API项目
API1使用5001端口
API2使用5002端口,为了有所区别,改下返回数据
// GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2","value3" }; }
新建asp.net core 空项目APIGate
修改Program
public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureAppConfiguration((hostingContext, config) => { config .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("appsettings.json", true, true) .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) .AddJsonFile("configuration.json") .AddEnvironmentVariables(); }) .UseStartup<Startup>() .Build();
修改Startup
public void ConfigureServices(IServiceCollection services) { services.AddOcelot(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseOcelot().Wait(); }
添加configuration.json
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/values", "DownstreamScheme": "http", "UpstreamPathTemplate": "/api/values", "UpstreamHttpMethod": [ "Get" ], "DownstreamHostAndPorts": [ { "Host": "localhost", } ] }, { "DownstreamPathTemplate": "/api/values", "DownstreamScheme": "http", "UpstreamPathTemplate": "/api/values2", "UpstreamHttpMethod": [ "Get" ], "DownstreamHostAndPorts": [ { "Host": "localhost", } ] } ], "GlobalConfiguration": { } }
打开浏览器http://localhost:56235/api/values
打开http://localhost:56235/api/values2
结合Butterfly实现微服务跟踪
下载Butterfly:https://github.com/ButterflyAPM/butterfly/releases
解压后执行
dotnet Butterfly.Web.dll --EnableHttpCollector=true
这里要主要加上后面的参数,否则是监控不到Http的请求的
接下来在API网关和API服务处添加Butterfly包
Install-Package Butterfly.Client.AspNetCore
在API网关Startup中添加服务
public void ConfigureServices(IServiceCollection services) { //your other code services.AddButterfly(option => { option.CollectorUrl = "http://localhost:9618"; option.Service = "my service"; }); }
在API服务中添加代码同上,只是服务名不同
修改configuration.json,开启tracing
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/values", "DownstreamScheme": "http", "UpstreamPathTemplate": "/api/values", "UpstreamHttpMethod": [ "Get" ], "DownstreamHostAndPorts": [ { "Host": "localhost", } ], "HttpHandlerOptions": { "UseTracing": true } }, { "DownstreamPathTemplate": "/api/values", "DownstreamScheme": "http", "UpstreamPathTemplate": "/api/values2", "UpstreamHttpMethod": [ "Get" ], "DownstreamHostAndPorts": [ { "Host": "localhost", } ], "HttpHandlerOptions": { "UseTracing": true } } ], "GlobalConfiguration": { } }
按上文请求http://localhost:56235/api/values2,然后打开http://localhost:9618/tracing/traces
可以看到已经跟踪到了请求
点击进去可以看到服务的调用
接下来按https://github.com/ButterflyAPM/butterfly-csharp 开启5001和5002,然后访问http://localhost:56235/api/values