Ocelot使用

时间:2023-03-10 02:14:03
Ocelot使用

1、在网关项目中通过nuget引入Ocelot

2、Startup.cs文件代码调整

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Ocelot.DependencyInjection;
using Ocelot.Middleware; namespace ApiGateway
{
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
//通过nuget引入如下包
//Microsoft.Extensions.Options.ConfigurationExtensions
//Microsoft.Extensions.Configuration.Json var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("configuration.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json"); Configuration = builder.Build();
} public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddOcelot(Configuration);
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
} app.UseOcelot();
app.UseHttpsRedirection();
app.UseMvc();
}
}
}

3、添加网关支持配置configuration.json

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/order", /*下游路径模板*/
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9001
}
],
"UpstreamPathTemplate": "/order", /*上游路径模板*/
"UpstreamHttpMethod": [ "Get" ]
}, {
"DownstreamPathTemplate": "/api/product",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 9002
}
],
"UpstreamPathTemplate": "/product",
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"RequestIdKey": "OcRequestId",
"AdministrationPath" : "administration"
}
}

4、运行网关项目验证,访问http://localhost:9000/product进行验证,localhost:9000是你网关项目的host

参考链接:https://www.cnblogs.com/yotsuki/p/7928095.html