搭建3個項目,分別是OcelotDemo、ServerApi1和ServerApi2這3個項目。訪問都是通過OcelotDemo進行輪訓轉發。
代碼案例鏈接:https://download.csdn.net/download/ly1h1/90715035
1.架構圖
?2.解決方案結構
3.步驟一,添加Nuget包
4.步驟二,配置ocelot.json
{"Routes": [{"DownstreamPathTemplate": "/api/values/{action}","DownstreamScheme": "http","DownstreamHostAndPorts": [{"Host": "localhost","Port": 5000}, // ServerAPI1{"Host": "localhost","Port": 8016} // ServerAPI2],"UpstreamPathTemplate": "/balanced-api/values/{action}","UpstreamHttpMethod": [ "GET", "POST" ],"LoadBalancerOptions": {"Type": "RoundRobin" // 輪詢策略}}],"GlobalConfiguration": {"BaseUrl": "http://localhost:8080"}
}
5.編寫OcelotDemo的Program
using Ocelot.DependencyInjection;
using Ocelot.Middleware;var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot(builder.Configuration);var app = builder.Build();
if (app.Environment.IsDevelopment())
{app.UseDeveloperExceptionPage();
}
await app.UseOcelot();
app.Run("http://localhost:8080");
5.步驟三,編寫ServerApi1的接口
using Microsoft.AspNetCore.Mvc;
using ServerAPI1.Models;namespace ServerAPI1.Controllers
{[ApiController][Route("api/[controller]")][Produces("application/json")]public class ValuesController : ControllerBase{/// <summary>/// 獲取服務基本信息/// </summary>[HttpGet("info")][ProducesResponseType(200)]public IActionResult GetInfo(){return Ok(new { Service = "ServerAPI1", Port = 5000 });}/// <summary>/// 計算服務 (A+B)/// </summary>/// <param name="model">輸入參數</param>[HttpPost("calculate")][ProducesResponseType(200)][ProducesResponseType(400)]public IActionResult Calculate([FromBody] TestModel model){if (!ModelState.IsValid) return BadRequest(ModelState);return Ok(new { Result = 123 + 321, Input = model });}}
}---------------------------
using System.ComponentModel.DataAnnotations;namespace ServerAPI1.Models
{public class TestModel{[Required][StringLength(100)]public string AAA { get; set; }[StringLength(200)]public string BBB { get; set; }}
}
6.步驟四,編寫ServerApi1的Program
var builder = WebApplication.CreateBuilder(args);// 添加Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{c.SwaggerDoc("v1", new() { Title = "ServerAPI1", Version = "v1" });
});builder.Services.AddControllers();
var app = builder.Build();// 配置Swagger
if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ServerAPI1 v1"));
}app.UseRouting();
app.MapControllers();
app.Run("http://localhost:5000");
步驟五,編寫Server2的接口
using Microsoft.AspNetCore.Mvc;
using ServerAPI2.Models;namespace ServerAPI2.Controllers
{[ApiController][Route("api/[controller]")][Produces("application/json")]public class ValuesController : ControllerBase{/// <summary>/// 獲取服務元數據/// </summary>[HttpGet("info")][ProducesResponseType(200)]public IActionResult GetInfo(){return Ok(new { Service = "ServerAPI2", Port = 8016 });}/// <summary>/// 字符串轉換服務/// </summary>/// <param name="model">輸入參數</param>[HttpPost("calculate")][ProducesResponseType(200)][ProducesResponseType(400)]public IActionResult Transform([FromBody] TestModel model){if (!ModelState.IsValid) return BadRequest(ModelState);return Ok(new { Result = $"{model.AAA}-{model.BBB}".ToUpper() });}}
}
----------------------------
using System.ComponentModel.DataAnnotations;namespace ServerAPI2.Models
{public class TestModel{[Required][StringLength(100)]public string AAA { get; set; }[StringLength(200)]public string BBB { get; set; }}
}
7.步驟六,編寫ServerAPI2的Program
var builder = WebApplication.CreateBuilder(args);// 添加Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{c.SwaggerDoc("v1", new() { Title = "ServerAPI2", Version = "v1" });
});builder.Services.AddControllers();
var app = builder.Build();// 配置Swagger
if (app.Environment.IsDevelopment())
{app.UseSwagger();app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ServerAPI2 v1"));
}app.UseRouting();
app.MapControllers();
app.Run("http://localhost:8016");
8.測試
采用PostMan直接訪問http://localhost:8080/balanced-api/values/info
可實現Server1和Server2的輪詢調用。
9.如果需要網關地址和服務是一對一
{"Routes": [{"DownstreamPathTemplate": "/api/values/{action}","DownstreamScheme": "http","DownstreamHostAndPorts": [{"Host": "localhost","Port": 5000}],"UpstreamPathTemplate": "/service1/api/values/{action}","UpstreamHttpMethod": [ "GET", "POST" ]},{"DownstreamPathTemplate": "/api/values/{action}","DownstreamScheme": "http","DownstreamHostAndPorts": [{"Host": "localhost","Port": 8016}],"UpstreamPathTemplate": "/service2/api/values/{action}","UpstreamHttpMethod": [ "GET", "POST" ]}],"GlobalConfiguration": {"BaseUrl": "http://localhost:8080"}
}