基于netcore的微服务——Ocelot(4)

一、使用背景

当在只使用了Consul的基础上微服务存在的缺点

1. 对于只有Consul的微服务系统,使用服务名就可访问,
但对于手机电脑,web等外部访问者,仍需要记忆服务器地址,端口号等。
一旦内部发生改变,会很麻烦,而且内部系统不希望直接被外部访问
2. 各个业务系统无法自由维护自己负责的服务器
3. 现在架构下的微服务都是对外开放,没有缺陷校验,如果每个服务都做校验工作量大
4. 很难做限流,收费等。

二、Ocelot的基本配置

1.创建一个空项目

2.Program.cs

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                //设置启动地址
            .UseUrls("http://127.0.0.1:8888")
            //加载 配置文件
            .ConfigureAppConfiguration((hostingContext,builder)=>
            {
                //加载configuration.json这个文件
                //为了确保会拷到bin/debug下,需要设置较新则复制
                builder.AddJsonFile("configuration.json",false,true);
            });

3.配置文件

{
  "ReRoutes": [
    {
      //Ocelot转发     到本地的5001端口的地址     ...../MsgService/abc   ----》  localhost:5001/api/abc
      "DownstreamPathTemplate": "/api/{url}",
      //请求的方式
      "DownstreamScheme": "http",
      //请求的主机和端口
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5001
        }
      ],
      //客户端请求的路由
      "UpstreamPathTemplate": "/MsgService/{url}",
      //允许的请求方式
      "UpstreamHttpMethod": [ "Get", "Post" ]
    },
    {
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5003
        }
      ],
      "UpstreamPathTemplate": "/ProductService/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ]
    }
  ]
}

4.Startup.cs

(1) 注入配置

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

        public IConfiguration Configuration { get; }

(2)注册Ocelot服务

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddOcelot(Configuration);
        }

(3)使用服务

 app.UseOcelot().Wait();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有诗亦有远方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值