3.1 场景描述
建3个站点,2个微服务站点,1个网关
在浏览器里访问 https://localhost:7227/api/Product/test1 会输出test1
在浏览器里访问https://localhost:7019/api/order/test2 会输出 test2
我要达到的效果是:
访问https://localhost:7055/Product/test1 调用https://localhost:7227/api/Product/test1 会输出test1
访问https://localhost:7055/order/test2 调用 https://localhost:7019/api/order/test2 会输出 test2
3.2 新建号这3个站点,在gateway1 这个站点通过nuget 添加ocelot
3.3 配置
3.3.1 在 appsettings.json 配置网关和微服务之间的映射
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Routes": [
{
"DownstreamPathTemplate": "/api/Product/{everything}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7227
}
],
"UpstreamPathTemplate": "/product/{everything}",
"UpstreamHttpMethod": [ "GET" ]
},
{
"DownstreamPathTemplate": "/api/Order/{everything}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 7019
}
],
"UpstreamPathTemplate": "/order/{everything}",
"UpstreamHttpMethod": [ "GET" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:7055"
}
}
3.3.2 在 program 里配置服务
加两行代码
builder.Services.AddOcelot();
app.UseOcelot().Wait();
下面是完整的program代码
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddOcelot();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.UseOcelot().Wait();
app.Run();
3.4 测试效果
访问https://localhost:7055/Product/test1 调用https://localhost:7227/api/Product/test1 会输出test1
访问https://localhost:7055/order/test2 调用 https://localhost:7019/api/order/test2 会输出 test2
标签:test1,网关,test2,https,app,配置,api,ocelot,localhost From: https://www.cnblogs.com/wangtiantian/p/18009195