
yum instarll wget -y
yum instarll unzip -y
wget  https://releases.hashicorp.com/consul/1.7.2/consul_1.7.2_linux_amd64.zip
unzip consul_1.7.2_linux_amd64.zip
mv consul /usr/local/bin/
consul -v 查看图一代表安装成功了
nohup consul agent -server -ui -bootstrap-expect=1 -data-dir=/tmp/consul  -node=consul-1 -client=0.0.0.0   -datacenter=dc1 & 后台启动会生成一个nohup.out的日子文件
curl http://127.0.0.1:8500/ui/dc1/services  访问 如下图二代表服务启动OK
consul可以通过配置文件注册服务,我这里用的是api代码注册
配置文件注册vi /etc/consul/services_config.json创建配置文件重启即可
图一

图二





       private static void ServiceRegister(IConfiguration configuration)
        {
            
            ConsulClient client = new ConsulClient(new Action<ConsulClientConfiguration>(t => {
                t.Address = new Uri(configuration["consul:servicesAddr"]);//这是Consul的服务地址192.168.31.140
                t.Datacenter = configuration["consul:datacenter"];//储存名
            }));           
            //注册一个实例
            var result = client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                Address = configuration["ip"], //注册服务的IP
                ID = $"{configuration["consul:serviceName"]}{configuration["id"]}",//服务id唯一的
                Name = configuration["consul:serviceName"],//服务名
                Port = Convert.ToInt32(configuration["port"]),//端口
                Tags = null,
                Check = new AgentServiceCheck()
                {
                    HTTP = $"http://{configuration["ip"]}:{configuration["port"]}{configuration["consul:healthCheck"]}",//健康检查的API地址
                    Interval = new TimeSpan(0, 0, 10),//间隔多少检查一次
                    DeregisterCriticalServiceAfter = new TimeSpan(0, 1, 0) //多久注销不健康的服务
                }
            }).Result;
        }

new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddCommandLine(args).Build();

  "consul": {
    "servicesAddr": "http://192.168.31.140:8500",
    "datacenter": "dr1",
    "serviceName": "ServiceCommodity",
    "healthCheck": "/api/Health"
  }

dotnet ServiceCommodity.dll --urls http://*:5000  --environment Development --ip 192.168.31.137 --port 5000 --id 1
dotnet ServiceCommodity.dll --urls http://*:5001  --environment Development --ip 192.168.31.137 --port 5001 --id 2
dotnet ServiceCommodity.dll --urls http://*:5002  --environment Development --ip 192.168.31.137 --port 5002 --id 3
dotnet ServiceUser.dll --urls http://*:6000  --environment Development --ip 192.168.31.137 --port 6000 --id 1
dotnet ServiceUser.dll --urls http://*:6001  --environment Development --ip 192.168.31.137 --port 6001 --id 2
dotnet ServiceUser.dll --urls http://*:6002  --environment Development --ip 192.168.31.137 --port 6002 --id 3




{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{controller}",//你的api路径
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/dust/{controller}",//你映射的路径
      "UpstreamHttpMethod": [ "get", "post" ],//请求方法
      "ServiceName": "ServiceCommodity",//你的服务名称
      "LoadBalancerOptions": {
        "Type": "LeastConnection"//ocelot提供了几种均衡方法,这里用的是最小连接
      }
    },
    {
        "DownstreamPathTemplate": "/api/{controller}",
        "DownstreamScheme": "http",
        "UpstreamPathTemplate": "/dust1/{controller}",
        "UpstreamHttpMethod": [ "get", "post" ],
        "ServiceName": "ServiceUser",
        "LoadBalancerOptions": {
          "Type": "LeastConnection"
        }
    }
  ],
  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Host": "192.168.31.140",//你的Consul的ip地址
      "Port": 8500,//你的Consul的端口
      "ConfigurationKey": "Consul"//指定Consul,ocelot提供了几种,可以去官网看看
    }
  }
}
  .ConfigureAppConfiguration((hostingContext, config) =>
               {
                   config
                       .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                       .AddJsonFile("appsettings.json", true, true)
                       .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                       .AddJsonFile("ocelot.json")
                       .AddEnvironmentVariables();
               })

启动 dotnet GateWayOcelot.dll --urls http://*:7000  

  string[] userAry = null;
            string[] commodityAry = null;
            using (HttpClient httpClient = new HttpClient()) 
            {
                HttpResponseMessage httpResponseMessage  = httpClient.GetAsync("http://192.168.31.137:7000/dust1/user").Result;
                userAry = JsonConvert.DeserializeObject<string[]>(httpResponseMessage.Content.ReadAsStringAsync().Result);
            }
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage httpResponseMessage = httpClient.GetAsync("http://192.168.31.137:7000/dust/commodity").Result;
                commodityAry = JsonConvert.DeserializeObject<string[]>(httpResponseMessage.Content.ReadAsStringAsync().Result);
            }
            this.ViewBag.msgText = $"{userAry[0]}和{userAry[1]}讨论项目,去烧烤摊点了{commodityAry[0]},{commodityAry[1]},{commodityAry[2]},第二天凌晨5点两个人支起了早餐摊!";

到此一个简单的微服务OK了
Demo下载地址
Asp.Net Core Ocelot Consul 微服务
原文:https://www.cnblogs.com/SuperDust/p/12595299.html