.Net Core微服务入门——Ocelot API网关接入(一)

2023-05-16

.Net Core微服务入门——Ocelot API网关接入

上一章我们测试了一个简单的Client 端访问Consul实现服务注册与发现,但是现实生产环境我们直接通过Client自行连接Consul实现服务注册与发现,基本是不可行的,我们需要一个统一的入口来连接客户端与服务,统一管理,并做安全认证等。

所以,这里就需要用到Ocelot

Ocelot
官网:https://ocelot.readthedocs.io/
Ocelot正是为.Net微服务体系提供一个统一的入口点,称为:Gateway(网关)。

新建Ocelot项目

1、创建一个空的asp.net core web项目。

在这里插入图片描述
2、引入Ocelot包:
在这里插入图片描述
3、新增ocelot.json,配置服务api信息:

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/product/getall",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        },
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "UpstreamPathTemplate": "/api/product/getall",
      "UpstreamHttpMethod": [
        "Get"
      ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //负载均衡,轮询机制 LeastConnection/RoundRobin/NoLoadBalancer/CookieStickySessions
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5010"
  }
}

这里我们先忽略 Consul,采用直连API服务,因为Consul、Ocelot等组件都是可以独立存在的。

配置文件中的Routes节点用来配置路由:
Downstream代表下游,也就是服务实例,就是我们的服务api地址
如:http://192.168.8.61:5001/api/product/getall
Upstream代表上游,也就是提供给客户端调用的api地址
如:http://192.168.8.61:5010/api/product/getall,
如果这里改成 api1/product/getall,那么客户端访问的api地址就是 http://192.168.8.61:5010/api1/product/getall
上游的路径不一定要和下游一致,可自行配置

LoadBalancerOptions节点用来配置负载均衡:
Ocelot内置了 LeastConnection、RoundRobin、NoLoadBalancer、CookieStickySessions 4种负载均衡策略。
LeastConnection -最少连接,跟踪哪些服务正在处理请求,并把新请求发送到现有请求最少的服务上。该算法状态不在整个Ocelot集群中分布。
RoundRobin - 轮询可用的服务并发送请求。 该算法状态不在整个Ocelot集群中分布。
NoLoadBalancer - 不负载均衡,从配置或服务发现提供程序中取第一个可用的下游服务。
CookieStickySessions - 使用cookie关联所有相关的请求到制定的服务。

BaseUrl节点就是配置我们ocelot网关将要运行的地址。

4、修改Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("ocelot.json");
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

5、修改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)
    {
        //添加ocelot服务
        services.AddOcelot();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //设置Ocelot中间件
        app.UseOcelot().Wait();

    }
}

6、运行Oeclot项目

我们先手动运行 ,直接进入bin目录下,执行控制台命令:`dotnet Ocelot.APIGateway.dll --urls=“http://*:5010”

在这里插入图片描述
浏览器访问 http://192.168.8.61:5010/api/product/getall

在这里插入图片描述
这里说明Ocelot网关正常运行了,下一步,我们client接入网关

7、修改Client

IGatewayServiceHelper. cs

public interface IGatewayServiceHelper
    {
        /// <summary>
        /// 获取产品数据
        /// </summary>
        /// <returns></returns>
        Task<string> GetProduct();


        /// <summary>
        /// 获取服务列表
        /// </summary>
        void GetServices();
    }

GatewayServiceHelper.cs

 public class GatewayServiceHelper: IGatewayServiceHelper
    {
        public async Task<string> GetProduct()
        {
            var Client = new RestClient("http://localhost:5010");
            var request = new RestRequest("/api/product/getall", Method.GET);

            var response = await Client.ExecuteAsync(request);
            return response.Content;
        }

        public void GetServices()
        {
            throw new NotImplementedException();
        }
    }

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        注入IServiceHelper
        //services.AddSingleton<IServiceHelper, ServiceHelper>();

        //注入IServiceHelper
        services.AddSingleton<IGatewayServiceHelper, GatewayServiceHelper>();

        注入IServiceHelper
        //services.AddSingleton<IServiceHelper, GatewayServiceHelper>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    //public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceHelper serviceHelper)
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        //程序启动时 获取服务列表
        //serviceHelper.GetServices();
    }
}

ProductsController.cs

[Produces("application/json")]
[Route("product")]
 public class ProductsController
 {
     private readonly IGatewayServiceHelper _serviceHelper;

     public ProductsController(IGatewayServiceHelper serviceHelper)
     {
         _serviceHelper = serviceHelper;
     }
     /// <summary>
     /// 获取产品列表
     /// </summary>
     /// <returns>产品列表</returns>
     [Route("GetAll")]
     [HttpGet]
     public List<Product> GetAllProducts()
     {
         var result = _serviceHelper.GetProduct();
         if (!string.IsNullOrWhiteSpace(result.Result))
         {
             var json = result.Result;
             //将Json转换回图书列表
             var products = JsonConvert.DeserializeObject<List<Product>>(json);
             return products;
         }

         return null;
     }
 }

调试启动Client,浏览器自动打开:https://localhost:44393/product/getall

在这里插入图片描述
Client顺利连上了网关层。

有人问,那我api有多个接口怎么办呢,总不能每个接口都配置一下吧。
多个接口的话,只需要修改ocelot.json即可,将具体api接口 改成 api/{url}

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        },
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "UpstreamPathTemplate": "/api/{url}",
      "UpstreamHttpMethod": [
        "Get"
      ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //负载均衡,轮询机制 LeastConnection/RoundRobin/NoLoadBalancer/CookieStickySessions
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5010"
  }
}

那如果有多个Service呢

{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        },
        {
          "Host": "localhost",
          "Port": 5002
        }
      ],
      "UpstreamPathTemplate": "/api/{url}",
      "UpstreamHttpMethod": [
        "Get"
      ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //负载均衡,轮询机制 LeastConnection/RoundRobin/NoLoadBalancer/CookieStickySessions
      }
    },
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5005
        },
        {
          "Host": "localhost",
          "Port": 5006
        }
      ],
      "UpstreamPathTemplate": "/api/{url}",
      "UpstreamHttpMethod": [
        "Get"
      ],
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //负载均衡,轮询机制 LeastConnection/RoundRobin/NoLoadBalancer/CookieStickySessions
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5010"
  }
}

下一章,我们将继续深入,探讨Ocelot 连接 Consul,服务治理等

https://blog.csdn.net/weixin_41003771/article/details/119177786

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

.Net Core微服务入门——Ocelot API网关接入(一) 的相关文章

  • 使用telnet通过SMTP协议发送邮件

    1 确认本地电脑的telnet服务是否打开 2 查看邮箱授权码是否设置 在图片中有提示 xff0c 授权码是用于登录第三方邮件客户端的专用密码 xff0c 这样可以保护自己的密码不被泄露 xff0c 还能委托其他客户端进行邮件的操作 如果没
  • 在Linux环境下使用命令行编译运行C源文件

    1 安装gcc 首先如何确定是否已经安装gcc了呢 xff1f 如果有一个hello c的源文件 xff0c 那么使用命令gcc hello c 如果报出提示 xff0c command gcc not found就是代表没有安装这个程序
  • C语言的指针传递和C++的引用传递

    首先 xff0c C语言没有引用传递 C 43 43 中使用引用传递的方式是在函数的参数前加 amp 号 xff0c 如 xff1a void Delete X LinkList amp L ElemType x 声明 Delete X L
  • python 安装pandas失败的解决办法

    python 安装pandas失败的解决办法 1 首先用CMD进行安装 xff0c 安装失败 2 然后用pycharm进行安装 xff0c 同样也失败 图片省略 3 最后在pycharm中添加清华源网址 https pypi tuna ts
  • docker 容器的启动、停止和删除

    1 查看所有docker容器 查看所有在运行的容器 xff1a docker ps 查看所有容器 包括停止的 docker ps a 来看看他们的区别 xff1a 2 启动容器 这里我来启动第二个Redis容器 xff08 因为我已经有一个
  • 用real vnc连接服务器

    用real vnc连接服务器 xff08 一 xff09 在无法访问服务器内部网络 首先 xff0c 本地电脑需要可以ping通服务器的IP xff0c 像学校的服务器 xff0c 一般只能用学校的网络才能访问 xff0c 若在校外 xff
  • nginx配置ssl证书实现https访问

    配置ssl证书之前 xff0c 先准备SSL证书 xff0c 至于获取的途径很多 xff08 阿里云的服务 xff0c 第三方服务购买 xff09 这里不详细解释 以下是我的SSL证书 准备好证书后 xff0c 找到nginx的安装目录 x
  • 棋牌游戏算法——麻将系列总结

    麻将介绍 麻将的基本规则都是一样的 xff0c 我就不累赘了 我从事棋牌工作五年了 xff0c 开发过无数的麻将玩法 xff0c 如柳州麻将 xff0c 转转麻将 xff0c 红中麻将 xff0c 来宾麻将 xff0c 广东麻将 xff0c
  • Docker run 命令详解

    命令格式 xff1a docker run OPTIONS IMAGE COMMAND ARG Usage Run a command in a new container 中文意思为 xff1a 通过run命令创建一个新的容器 xff08
  • ROS笔记——创建简单的主题发布节点和主题订阅节点

    在安装好ROS后 xff0c 接着学习如何创建节点和节点之间的通信方式 xff0c 以一个简单的主题发布节点和主题订阅节点说明 节点是连接ROS网络等可执行文件 xff0c 是实现某些功能的软件包 xff0c 也是一个主要计算执行的进程 一
  • SVN常用命令总结

    svn使用总结 SVN检出操作 svn checkout path svn checkout svn 192 168 0 1 project 简写 xff1a svn co SVN查看状态 span class token string 3
  • vue-cli3搭建的vue改造成SSR项目

    vue cli3搭建的vue改造成SSR项目 一 文章简介二 搭建vue项目三 改造成SSR首先安装ssr的所需相关依赖改造router ts改造store ts改造main ts创建entry client ts创建entry serve
  • VSCode配置Git随记

    vscode中对git进行了集成 很多操作只需点击就能操作 无需写一些git指令 不过这就需要你对vscode进行配置 下面我会讲到git的配置与免密码上传github 一 安装Git管理工具 可上官网安装 安装路径Git 安装路径默认C
  • VSCode插件推荐(2018.5.31)

    前言 vscode我觉得是用过最好用的编辑器 xff0c 相对而言没有webStorm myeclipse那么卡 xff0c 而且最主要是免费的 xff0c 不用烦每次更新软件的时候破解码无法使用 xff0c 这篇博客主要是记录我自己发现的
  • VSCode配置 Debugger for Chrome插件

    Debugger for Chrome这个插件是直接在vscode里面进行调试js文件 xff0c 跟谷歌的控制台是一样的功能 xff0c 下载了它就不用打开浏览器的控制台就能进行打断点 首先在左侧扩展栏找到这个插件下载好了后重启编辑器之后
  • VSCode打开vue项目的vue组件提示错误的解决办法及key属性的作用

    本博文为学习过程中随记 xff0c 如有抄袭请评论告知谢谢 xff01 最近重新拾起了vue项目 xff0c 因为之前开始习惯使用VSCode编码 xff0c 因此在打开vue项目时 xff0c vue的语法v for默认报错 以下是解决方
  • vue搭建脚手架及部署vue项目随记

    本博文是用于介绍搭建vue脚手架及使用webpack部署vue脚手架目录 1 依赖软件 Node js 1 1下载node js http nodejs cn download https npm taobao org mirrors no
  • 最新版XAMPP中php7.2配置mongodb3.6扩展

    本博文为本人配置mongo随记 第一步下载xampp xff0c 地址 xff1a https www apachefriends org zh cn download html xff0c 这里我下载的是最新版php7 2 8 安装完之后
  • nginx的进程模型

    文章目录 一 Nginx进程模型master进程worker进程示意图 二 Nginx reload配置文件过程三 worker进程处理请求的过程四 Nginx多进程模型的好处 一 Nginx进程模型 Nginx启动后 xff0c 以dae
  • 基于docker的github升级之路

    基于docker的github升级之路 公司的gitlab目前的版本是8 13 2 xff0c 运行在docker容器内 该版本使用的api版本是V3 xff0c 已经不适合一些监控统计工具的调用了 xff0c 看了gitlab官网上对最新

随机推荐

  • .frm,.myd,myi转换为.sql导入数据库

    先说说这几种文件是干什么的 xff1a frm是描述了表的结构 xff0c myd保存了表的数据记录 xff0c myi则是表的索引 其实一个 frm文件就是对应的数据库中的一个表 表示数据表的表结构 MYD文件 这应该是INNODB引擎外
  • linux idea无法输入中文

    linux idea无法输入中文 1 系统输入法切换快捷键 xff08 ctrl 43 space xff09 与idea快捷键冲突 xff0c 更改输入法快捷键 xff0c 如改为 ctrl 43 6
  • linux设置systemd服务

    linux设置systemd服务 access dir etc systemd system create file whose name ended with service chmod 644 xx service edit xx se
  • 普通用户使用docker命令

    普通用户使用docker命令 add docker group sudo cat etc group docker sudo groupadd g 999 docker add user to docker group sudo gpass
  • samba服务器

    samba服务器 install samba edit etc samba smb conf default comment 61 default path 61 opt es backups valid users 61 zsk13 wr
  • linux安装mongodb

    install mongodb tar zxvf mongodb linux x86 64 4 0 22 tgz useradd mongod init passwd with mongod passwd mongod mkdir for
  • linux制作iso启动盘

    制作iso启动盘 sudo fdisk l umount dev sdb umount dev sdb1 umount dev sdd2 umount dev sdd3 sudo mkfs ext4 dev sdb sudo dd if 6
  • ros2+opencv抓取rtsp视频流

    遇到的坑 xff1a rtsp视频流和转ros2 topic放到一个线程里 xff0c 频繁提示解码丢帧的情况 解决这个问题需要将opencv获取rtsp视频流单独开一个线程 xff0c 不能在里面处理任何多余的代码 代码如下 xff1a
  • 机械臂标定实战

    硬件资源 xff1a 机械臂viper300 摄像头realsense d435i 软件版本 xff1a 操作系统 xff1a Ubuntu18 04 ROS Melodic 标定算法 xff1a 采用easy handeye 算法包 ht
  • Linux 下的 Docker 安装及创建私有仓(三)

    Linux 下的 Docker 安装及创建私有仓 xff08 三 xff09 辛苦打工人 xff0c 今天继续搬砖 xff0c 搞搞私有仓用户和密码 废话不说 xff0c 开工 xff01 1 安装httpd tools 授权需要用到 xf
  • .Net Core Web API 发布到Linux Docker(一)

    Net Core Web API 发布到Linux Docker xff08 一 xff09 Net Core Web API 项目已经建好 xff0c 想要发布到Linux Docker 上 xff0c 具体研究了一下 xff0c 发现有
  • 设置mysql允许外网访问

    mysql的root账户 我在连接时通常用的是localhost或127 0 0 1 公司的测试服务器上的mysql也是localhost所以我想访问无法访问 测试暂停 解决方法如下 1 修改表 登录mysql数据库 切换到mysql数据库
  • .Net Core Web API 发布到Linux Docker(二)

    Net Core Web API 发布到Linux Docker xff08 二 xff09 本章将尝试 Net Core Web API 直接发布到私有仓 Net Core Web API 直接发布到Docker私有仓 1 选择需要发布的
  • .Net Core微服务入门——Consul集群搭建(一)

    Net Core微服务入门 Consul集群搭建 xff08 一 xff09 前几天一直在本地机器试用Consul xff0c 今天特意在服务器上试试 xff0c 并搭建下集群 一 服务器安装consul 获取镜像 docker pull
  • .Net Core微服务入门——Consul集群搭建(二)

    Net Core微服务入门 Consul集群搭建 xff08 二 xff09 1 先启动第一个consul服务 xff1a consul1 docker run name consul1 d p 8500 span class token
  • .Net Core微服务入门——Consul集群搭建(三)

    Net Core微服务入门 Consul集群搭建 xff08 三 xff09 本章将介绍 Consul 集群 Client 还记得第一篇中 xff0c 我们再Consul中启动了2个MyAPI服务么 xff0c 我们重启下 xff0c 看下
  • .Net Core微服务入门——Consul集群搭建(四)

    Net Core微服务入门 Consul集群搭建 xff08 四 xff09 多台服务器集群搭建 1 先关闭几台集群服务器防火墙 当然 xff0c 不关闭也可以 xff0c 那就必须开通端口权限 consul 涉及的端口 xff1a 850
  • Docker 同一主机容器间通信

    Docker 容器间通信 本文我们采用bridge网络通信 1 创建bridge网络 docker network create testnet 2 查看Docker网络 docker network ls 3 运行容器连接到testnet
  • Centos7端口查看开放,防火墙开启关闭命令等

    1 开放 关闭端口 开放5001端口 firewall cmd zone 61 public add port 61 5001 tcp permanent 关闭5001端口 firewall cmd zone 61 public remov
  • .Net Core微服务入门——Ocelot API网关接入(一)

    Net Core微服务入门 Ocelot API网关接入 上一章我们测试了一个简单的Client 端访问Consul实现服务注册与发现 xff0c 但是现实生产环境我们直接通过Client自行连接Consul实现服务注册与发现 xff0c