基于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();
posted @ 2022-05-23 10:28  有诗亦有远方  阅读(29)  评论(0)    收藏  举报  来源