本文章不做Ocelot的介绍及它能做什么,如果想了解理论知识的话可查看官方文档;
这是部署Ocelot时的结构图,下面进入实战完成这张图的部署;
一、创建微服务项目
从上图来看,我们需要创建三个项目分别:
注意,建议创建core 2.1版本,3.0暂未稳定;
OcelotService (Ocelot服务网关)
ClientService (服务1)
ProudctService (服务2)
二、创建Ocelot配置文件
在OcelotService网关项目中,configuration.json的文件;并将文件属性 “复制到输出目录” 修改为:如果较新则复制
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/values",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 56688
}
],
"UpstreamPathTemplate": "/ClientService/values",
"UpstreamHttpMethod": [ "Get" ]
},
{
"DownstreamPathTemplate": "/api/values",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 56746
}
],
"UpstreamPathTemplate": "/ProducService/values",
"UpstreamHttpMethod": [ "Get" ]
}
]
}
- DownstreamPathTemplate:下游请求模板 (url)
- DownstreamScheme:下游服务schema (http、https)
- DownstreamHostAndPorts:下游服务地址
- UpstreamPathTemplate:上游请求模板(url)
- UpstreamHttpMethod:上游请求方式(get、post等)
- 更多属性可查看官方文档介绍
三、安装Ocelot
Nuget>Install-Package Ocelot
Nuget>Install-Package Ocelot.Provider.Consul
1、修改Program及Startup文件
public class Program
{
public static void Main(string[] args)
{
CreateWebHost(args).Run();
}
public static IWebHost CreateWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://{IP}:{Port}")
.ConfigureAppConfiguration((hostionContext, builder) =>
{
builder
.SetBasePath(hostionContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("configuration.json", false, true)
.AddEnvironmentVariables();
})
.Build();
}
}
2、注入Ocelot
public void ConfigureServices(IServiceCollection services)
{
services.AddOcelot(Configuration).AddConsul();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseOcelot().Wait();
}
Ocelot配置已经完成,最后我们修改一下另外两个服务的输出数据,方便测试查看;
打开解决方案的属性,启动多项目运行
在Ocelot网关Api项目地址栏中访问其他服务,我们只需要消费那个Service即可。
更多文档关注:dotnet跨平台