欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

ocelot简单例子

时间:2023-05-18

环境:
目标框架 .NET Core 2.1
控制台应用程序
Ocelot 8.0.3

.NET Core 2.1的运行方式为:
找到编译后的dll,
打开cmd命令行,
输入:dotnet Gateway.dll
如果缺少环境,按cmd的提示进行环境安装

效果:
访问http://localhost:9000,
会随机路由到:
http://localhost:1000
http://localhost:1001

Startup.cs

using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.DependencyInjection;using Ocelot.DependencyInjection;using Ocelot.Middleware;namespace Gateway{ 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(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // 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(); } }}

Program.cs

using Microsoft.AspNetCore;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;namespace Gateway{ public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseUrls("http://*:9000") .ConfigureAppConfiguration((hostingContext, config) => { config .SetbasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("ocelot.json") .AddEnvironmentVariables(); }) .UseStartup (); }}

ocelot.json
1001,1002端口是我部署的两个简单html站点
负载均衡LoadBalancerOptions模式为轮流访问

{ "ReRoutes": [ { "DownstreamPathTemplate": "/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 1001 }, { "Host": "localhost", "Port": 1002 } ], "LoadBalancerOptions": { "Type": "RoundRobin" }, "UpstreamPathTemplate": "/{everything}", "UpstreamHttpMethod": [ "Get" ] } ], "GlobalConfiguration": { }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。