asp.net core使用consul注册服务


上一篇 consul在centos7下实现集群 讲到consul的安装和集群,本次来说一下asp.net core使用consul注册服务

1. 准备

安装了consul的centos7系统

三个asp.net core api项目,其中一个网关项目,两个服务,一般微服务都会使用网关,所以这里也加上网关

项目将发布在本机IIS上(ip:192.168.1.155),consul在虚拟机(系统centos7,ip:192.168.253.128)

2. 代码

服务A:添加HealthController,健康检查用,然后发布到IIS,使用端口9001

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class HealthController : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok("ok");
}

服务B:与服务A一样,添加HealthController,内容一样,然后发布到IIS,使用端口9002

网关项目:nuget引用ocelot包,然后在项目根目录下添加ocelot.json文件

{
  "ReRoutes": [
    {
      "UpstreamPathTemplate": "/a/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9001
        }
      ]
    },
    {
      "UpstreamPathTemplate": "/b/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 9002
        }
      ]
    }
  ],
  "GlobalConfiguration": {
    
  }
}

然后在Startup的ConfigureServices方法中添加如下代码:

services.AddOcelot(new ConfigurationBuilder().AddJsonFile("ocelot.json", false, true).Build());

在Configure方法app.UseMvc()之前添加如下代码

app.UseOcelot().Wait();

发布网关项目到IIS,使用9000端口

通过locaohost:9000/a/health即可访问localhost:9001/api/health

通过locaohost:9000/b/health即可访问localhost:9002/api/health

3. consul服务注册(配置文件方式)

在 /etc/consul目录下创建consul_config.json

{
    "services":[
    {
        "id": "CLIENT_SERVICE_01",
        "name" : "ApiServiceA",
        "tags": [
            "ApiService_01"
        ],
        "address": "192.168.1.155",
        "port": 9001,
        "checks": [
            {
                "name": "clientservice_check",
                "http": "http://192.168.1.155:9001/api/health",
                "interval": "10s",
                "timeout": "5s"
            }
        ]
    },
    {
        "id": "CLIENT_SERVICE_02",
        "name" : "ApiServiceB",
        "tags": [
            "ApiService_02"
        ],
        "address": "192.168.1.155",
        "port": 9002,
        "checks": [
            {
                "name": "clientservice_check",
                "http": "http://192.168.1.155:9002/api/health",
                "interval": "10s",
                "timeout": "5s"
            }
        ]
    }]
}

然后执行

consul agent -server -ui -bootstrap-expect=1 -config-dir=/etc/consul -data-dir=/var/local/consul  -node=consul-128 -client=0.0.0.0  -bind=192.168.253.128 -datacenter=dc1

在浏览器中打开192.168.253.128:8500,可以看到服务A和服务B已经注册并能正常访问

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM