.Net Core 微服务架构基于Ocelot实现Api网关入门(一)

8 篇文章 2 订阅
2 篇文章 0 订阅

本文章不做Ocelot的介绍及它能做什么,如果想了解理论知识的话可查看官方文档;

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跨平台

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值