.netcore的微服务学习(三)--网关(gateway)之Ocelot+Consul学习

2021-01-16 20:15

阅读:741

标签:names   nta   baseurl   ***   --   net   get   localhost   注册   

一。我们用Ocelot加consul一起使用,服务的注册发现,而不是现在的单机版手动配置服务地址

我们写Ocelot的配置,这个是时候 我们要引用Ocelot.Provider.Consul这个包,然后又多一个扩展addConsul()这个扩展方法,如下startup的配置

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;

namespace OcelotDemo
{
    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.AddOcelot().AddConsul();
        }

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

配置文件的配置如下

//*****************************单地址多实例负载均衡+Consul********************************
{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/TestOcelotConsul/{url}", //网关地址--url变量
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "ServiceName": "TestConsulService", //consul服务名称,要对上consul组名称,集群的组
      "LoadBalancerOptions": {
        "Type": "RoundRobin" //轮询      LeastConnection-最少连接数的服务器   NoLoadBalance不负载均衡
      },
      "UseServiceDiscovery": true //服务发现
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://127.0.0.1:5003", //网关对外地址
    "ServiceDiscoveryProvider": {
      "Host": "localhost",
      "Port": 8500,
      "Type": "Consul" //由Consul提供服务发现
    }
  }
}

 二,配置好后,当然要启动consul,服务和网关,这个请看前两篇,然后我们直接访问一下地址

我们访问配置好的网关地址:http://localhost:5003/TestOcelotConsul/User/Get,然后会自动返回注册consul的服务地址

 

.netcore的微服务学习(三)--网关(gateway)之Ocelot+Consul学习

标签:names   nta   baseurl   ***   --   net   get   localhost   注册   

原文地址:https://www.cnblogs.com/May-day/p/13375203.html


评论


亲,登录后才可以留言!