参考大佬的博客写的:https://www.cnblogs.com/alan-lin/p/9126155.html;也可以参考这篇博客:https://www.cnblogs.com/axzxs2001/p/8487521.html
首先下载Consul: https://www.consul.io/downloads.html,本项目是windows下进行测试,然后把下载的添加到
的path中;这样的话环境变量接配置好了
项目结构如下:
加一个core的web空白项目TestApiGateway;在nuget中找到包ocelot;添加一个Ocelot.json的文件:
{ //路由配置 "ReRoutes": [ { "UpstreamPathTemplate": "/apiservice/{controller}/{action}", //请求路径模板 "UpstreamHttpMethod": [ "Get", "POST" ], //请求方法数组 "DownstreamPathTemplate": "/apiservice/{controller}/{action}", //下游请求地址模板 "DownstreamScheme": "http", //请求协议,目前应该是支持http和https "DownstreamHostAndPorts": [ //下游地址和端口 { "host": "localhost", "port": 5011 }, { "host": "localhost", "port": 5012 } ], "LoadBalancerOptions": { //负载均衡 RoundRobin(轮询)/LeastConnection(最少连接数)/CookieStickySessions(相同的Sessions或Cookie发往同一个地址)/NoLoadBalancer(不使用负载) "Type": "RoundRobin" } } ], "GlobalConfiguration": { //全局配置 "BaseUrl": "http://localhost:5000" //告诉别人网关对外暴露的域名 } }
然后修改俩个类如下:
public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build() .Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, builder) => { builder.SetBasePath(context.HostingEnvironment.ContentRootPath) .AddJsonFile("Ocelot.json");//testOcelot.json }) .UseKestrel() .UseUrls("http://localhost:5000") .UseStartup<Startup>(); }
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(); } // 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(); //app.Run(async (context) => //{ // await context.Response.WriteAsync("Hello World!"); //}); } }
这个这个网关项目基本就配置完了
现在添加两个api项目TestServiceA和TestServiceB,修改Startup的端口分别为5011和5012
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseUrls("http://localhost:5011") .UseStartup<Startup>();
这个是项目不是在debug启动下的端口配置,还需要修改appsettings.json文件如下,是为了区分调用的api是哪个
{ "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }, "AppName": "ServiceA" }
然后是接口的类容,只留下get和post请求即可,这个接口的返回结果可以修改,
[Route("apiservice/[controller]/[action]")] [ApiController] public class ValuesController : ControllerBase { public IConfiguration Configuration { get; } public ValuesController(IConfiguration configuration) { Configuration = configuration; } // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1A", "value2A" }; } // GET api/values/5 [HttpGet]//("{id}") public ActionResult<string> Getid(int id) { return HttpContext.Request.Host.Port + "=>" + Configuration["AppName"] + "=>" + DateTime.Now.ToString() + "=>" + id; } // POST api/values [HttpPost] public string Post(string value) { return HttpContext.Request.Host.Port + "=>" + Configuration["AppName"] + "=>" + DateTime.Now.ToString() + "=>" + value; } [HttpGet] public IActionResult Heathle() { return Ok(); } }
如果是要debug下启动项目测试:右键项目属性修改端口
测试效果如下:
这个接口就找轮播了
添加 Consul的支持
conf 配置目录
data 缓存数据目录,可清空里面内容
dist Consul UI目录
consul.exe 注册软件
startup.bat 执行脚本
修改配置文件service.json
{ "encrypt": "7TnJPB4lKtjEcCWWjN6jSA==", "services": [ { "id": "ApiServiceA", "name": "ApiServiceA", "tags": [ "ApiServiceA" ], "address": "localhost", "port": 5011, "checks": [ { "id": "ApiServiceA_Check", "name": "ApiServiceA_Check", "http": "http://localhost:5011/apiservice/values/heathle", "interval": "10s", "tls_skip_verify": false, "method": "GET", "timeout": "1s" } ] }, { "id": "API服务A", "name": "ApiServiceB", "tags": [ "ApiServiceB" ], "address": "localhost", "port": 5012, "checks": [ { "id": "ApiServiceB_Check", "name": "ApiServiceB_Check", "http": "http://localhost:5012/apiservice/values/heathle", "interval": "10s", "tls_skip_verify": false, "method": "GET", "timeout": "1s" } ] } ] }
修改startup.bat 脚本
consul agent -server -datacenter=dc1 -bootstrap -data-dir ./data -config-file ./conf -ui-dir ./dist -node=n1 -bind 127.0.0.1 -client=0.0.0.0
然后启动api服务和startup.bat 脚本,效果如下
最后这是在一个服务上的,要在多个服务商的参考:https://www.cnblogs.com/alan-lin/p/9126155.html,我也是按这个博客来写的demo,然后记个笔记;哈哈哈
ocelot配置文件基本参数,具体参考官方文档:https://ocelot.readthedocs.io/en/latest/index.html
{ "ReRoutes": [ //路由是API网关最基本也是最核心的功能、ReRoutes下就是由多个路由节点组成。 { "DownstreamPathTemplate": "", //下游服务模板 "UpstreamPathTemplate": "", //上游服务模板 "UpstreamHttpMethod": [ "Get" ],//上游方法类型Get,Post,Put "AddHeadersToRequest": {},//需要在转发过程中添加到Header的内容 "FileCacheOptions": { //可以对下游请求结果进行缓存,主要依赖于CacheManager实现 "TtlSeconds": 10, "Region": "" }, "ReRouteIsCaseSensitive": false,//重写路由是否区分大小写 "ServiceName": "",//服务名称 "DownstreamScheme": "http",//下游服务schema:http, https "DownstreamHostAndPorts": [ //下游服务端口号和地址 { "Host": "localhost", "Port": 8001 } ], "RateLimitOptions": { //限流设置 "ClientWhitelist": [], //客户端白名单 "EnableRateLimiting": true,//是否启用限流设置 "Period": "1s", //每次请求时间间隔 "PeriodTimespan": 15,//恢复的时间间隔 "Limit": 1 //请求数量 }, "QoSOptions": { //服务质量与熔断,熔断的意思是停止将请求转发到下游服务。当下游服务已经出现故障的时候再请求也是无功而返, 并且增加下游服务器和API网关的负担,这个功能是用的Polly来实现的,我们只需要为路由做一些简单配置即可 "ExceptionsAllowedBeforeBreaking": 0, //允许多少个异常请求 "DurationOfBreak": 0, //熔断的时间,单位为秒 "TimeoutValue": 0 //如果下游请求的处理时间超过多少则自如将请求设置为超时 } } ], "UseServiceDiscovery": false,//是否启用服务发现 "Aggregates": [ //请求聚合 { "ReRouteKeys": [ //设置需要聚合的路由key "booking", "passenger" ], "UpstreamPathTemplate": "/api/getbookingpassengerinfo" //暴露给外部的聚合请求路径 }, "GlobalConfiguration": { //全局配置节点 "BaseUrl": "https://localhost:5000" //网关基地址 } }
路由分开写要注意,不然报错
限流和聚合,聚合只能get请求,返回json类型
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/apiA/{controller}/{action}", //api地址 "UpstreamPathTemplate": "/api/{controller}/{action}", //请求输入的地址 "UpstreamHttpMethod": [ "Get", "POST" ], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5011 } ] }, { "DownstreamPathTemplate": "/apiB/{controller}/{action}", "UpstreamPathTemplate": "/api2/{controller}/{action}", "UpstreamHttpMethod": [ "Get", "POST" ], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5012 } ] }, { "DownstreamPathTemplate": "/apiA/Values/Get", "UpstreamPathTemplate": "/api/getbooking", "UpstreamHttpMethod": [ "Get" ], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5011 } ], "Key": "booking", "RateLimitOptions": { //限流 "ClientWhitelist": [], "EnableRateLimiting": true, "Period": "1s", "PeriodTimespan": 15, "Limit": 1 } }, { "DownstreamPathTemplate": "/apiB/Values/Get", "UpstreamPathTemplate": "/api/getpassenger", "UpstreamHttpMethod": [ "Get" ], "ReRouteIsCaseSensitive": false, "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port":