建立项目
- 新建Asp.net core Web 空项目,命名 OcelotService
- 添加Nuget包 - Ocelot.Provider.Consul
菜单:工具 / Nuget包管理器 / 管理解决方案的 Nuget 程序包
如图所示,在浏览标签中输入Ocelot.Provider.Consul,检索出对应的包后,点击安装
添加配置
新建一个 CoelotConfig.json 文件
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/{url}",//下游地址模板,转发模板
"DownstreamScheme": "http",//下游转发协议
"UpstreamPathTemplate": "/ApiA/{url}",//上游匹配模板
"UpstreamHttpMethod": [ "Get", "Post" ],//上游匹配协议
"UseServiceDiscovery": true,//是否进行服务发现
"ServiceName": "ApiA", //服务名称
"LoadBalancerOptions": {
"Type": "RoundRobin" //负载均衡,转徇
}
},
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/ApiB/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"UseServiceDiscovery": true,
"ServiceName": "ApiB",
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
],
"GlobalConfiguration": {//服务发现配置
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
}
}
载入配置文件
修改 Program.cs 文件
namespace OcelotService
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config=>config.AddJsonFile("OcelotConfig.json", true, true))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
注意:如果 AddJsonFile 方法不存在,引入 Microsoft.Extensions.Configuration.Json
Nuget包
启动 Ocelot 服务
修改 Startup.cs 文件
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().AddConsul();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseOcelot().Wait();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
致此,Ocelot 服务配置完成。