.net core微服务之服务发现

一:nacos

https://nacos.io/docs/latest/what-is-nacos/

https://github.com/alibaba/nacos

二:consul

https://developer.hashicorp.com/consul/docs?product_intent=consul

https://github.com/hashicorp/consul

服务发现的框架常用的还有zookeeper eureka等,这里准备使用nacos

前置条件准备 docker,yaml

复制代码
version: "3.8"
networks:
  caseor_bridge:
    driver: bridge
    ipam:
      config:
        - subnet: 172.0.10.0/24
  
services:

    mysql:
        container_name: mysql
        image: mysql
        privileged: true
        command: --character-set-server=utf8mb4 --collation-server=utf8mb4_general_ci --max_connections=2000 --max_allowed_packet=64M
        environment:
          - TZ=Asia/Shanghai
          - MYSQL_ROOT_PASSWORD=123456
        volumes:
          - ./mysql:/var/lib/mysql
        ports:
          - "3306:3306"
        healthcheck:
          test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
          interval: 5s
          timeout: 10s
          retries: 10
        networks:
          caseor_bridge:
            ipv4_address: 172.0.10.3

    redis:
        image: redis
        container_name: "redis"
        ports:
            - "6379:6379"
        volumes:
            - ./redis/data:/data
            - ./redis/conf:/usr/local/etc/redis
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.4

    nacos1:
        container_name: nacos1
        hostname: nacos1
        image: nacos/nacos-server
        environment:
            - MODE=cluster
            - PREFER_HOST_MODE=hostname
            - NACOS_SERVERS=nacos1:8848 nacos2:8848 nacos3:8848
            - SPRING_DATASOURCE_PLATFORM=mysql
            - MYSQL_SERVICE_HOST=172.0.10.3
            - MYSQL_SERVICE_PORT=3306
            - MYSQL_SERVICE_USER=root
            - MYSQL_SERVICE_PASSWORD=123456
            - MYSQL_SERVICE_DB_NAME=nacos
            - MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true  
            - JVM_XMS=128m
            - JVM_XMX=128m
            - JVM_XMN=128m
        volumes: 
            - ./nacos/cluster-logs/nacos1:/home/nacos/logs
            - ./nacos/init.d:/home/nacos/init.d
        ports: 
            - 8850:8848
            - 7850:7848     
            - 9870:9848
            - 9852:9849
        depends_on:
          - mysql
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.5

    nacos2:
        container_name: nacos2
        hostname: nacos2
        image: nacos/nacos-server
        environment:             
            - MODE=cluster
            - PREFER_HOST_MODE=hostname
            - NACOS_SERVERS=nacos1:8848 nacos2:8848 nacos3:8848
            - SPRING_DATASOURCE_PLATFORM=mysql
            - MYSQL_SERVICE_HOST=172.0.10.3
            - MYSQL_SERVICE_PORT=3306
            - MYSQL_SERVICE_USER=root
            - MYSQL_SERVICE_PASSWORD=123456
            - MYSQL_SERVICE_DB_NAME=nacos
            - MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true  
            - JVM_XMS=128m
            - JVM_XMX=128m
            - JVM_XMN=128m
        volumes: 
            - ./nacos/cluster-logs/nacos2:/home/nacos/logs
            - ./nacos/init.d:/home/nacos/init.d
        ports: 
            - 8849:8848
            - 7849:7848     
            - 9869:9848
            - 9851:9849
        depends_on:
          - mysql
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.6

    nacos3:
        container_name: nacos3
        hostname: nacos3
        image: nacos/nacos-server
        environment:             
            - MODE=cluster
            - PREFER_HOST_MODE=hostname
            - NACOS_SERVERS=nacos1:8848 nacos2:8848 nacos3:8848
            - SPRING_DATASOURCE_PLATFORM=mysql
            - MYSQL_SERVICE_HOST=172.0.10.3
            - MYSQL_SERVICE_PORT=3306
            - MYSQL_SERVICE_USER=root
            - MYSQL_SERVICE_PASSWORD=123456
            - MYSQL_SERVICE_DB_NAME=nacos
            - MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true  
            - JVM_XMS=128m
            - JVM_XMX=128m
            - JVM_XMN=128m
        volumes: 
            - ./nacos/cluster-logs/nacos3:/home/nacos/logs
            - ./nacos/init.d:/home/nacos/init.d
        ports: 
            - 8848:8848
            - 7848:7848     
            - 9848:9848
            - 9849:9849
        depends_on:
          - mysql
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.7

    etcd:
        container_name: etcd
        hostname: etcd
        image: bitnami/etcd
        volumes:
          - ./etcd/data:/bitnami/etcd
        environment:
          ETCD_ENABLE_V2: "true"
          ALLOW_NONE_AUTHENTICATION: "yes"
          ETCD_ADVERTISE_CLIENT_URLS: "http://etcd:2379" #https://github.com/apache/apisix-dashboard/issues/2756 需要更换为host域名不能使用0.0.0.0
          ETCD_LISTEN_CLIENT_URLS: "http://0.0.0.0:2379"
        ports:
          - "2379:2379/tcp"
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.8

    apisix:
        container_name: apisix
        hostname: apisix
        image: apache/apisix        
        volumes:
          - ./apisix/log:/usr/local/apisix/logs
          - ./apisix/conf/config.yaml:/usr/local/apisix/conf/config.yaml:ro
        depends_on:
          - etcd
        ports:
          - "9088:9088/tcp"
          - "9180:9180/tcp"
          - "127.0.0.1:9090:9090/tcp"
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.9
    
    apisix-dashboard:
        container_name: apisix-dashboard
        image: apache/apisix-dashboard
        depends_on:
          - etcd
        ports:
          - "9188:9188"
        volumes:
          - ./apisix/conf/dashboard.yaml:/usr/local/apisix-dashboard/conf/conf.yaml
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.10

    rabbitmq01:
      image: rabbitmq
      container_name: rabbitmq01
      hostname: rabbitmq01
      environment:
        - TZ=Asia/Shanghai
        - RABBITMQ_DEFAULT_USER=root   #自定义登录账号
        - RABBITMQ_DEFAULT_PASS=123456 #自定义登录密码
        - RABBITMQ_ERLANG_COOKIE='secret_cookie'
      ports:
        - "15672:15672"
        - "5672:5672"
      volumes:
        - ./rabbitmq/mq1/data:/var/lib/rabbitmq
        - ./rabbitmq/mq1/conf:/etc/rabbitmq
      command:  bash -c "sleep 10; rabbitmq-server;"
      networks:
        caseor_bridge:
            ipv4_address: 172.0.10.11

    rabbitmq02:
      image: rabbitmq
      container_name: rabbitmq02
      hostname: rabbitmq02
      environment:
        - TZ=Asia/Shanghai
        - RABBITMQ_DEFAULT_USER=root   #自定义登录账号
        - RABBITMQ_DEFAULT_PASS=123456 #自定义登录密码
        - RABBITMQ_ERLANG_COOKIE='secret_cookie'
      ports:
        - "15673:15672"
        - "5673:5672"
      depends_on:
          - rabbitmq01
      volumes:
        - ./rabbitmq/mq2/data:/var/lib/rabbitmq
        - ./rabbitmq/mq2/conf:/etc/rabbitmq
      command:  bash -c "sleep 10; rabbitmq-server;"
      networks:
        caseor_bridge:
            ipv4_address: 172.0.10.12

    rabbitmq03:
      image: rabbitmq
      container_name: rabbitmq03
      hostname: rabbitmq03
      environment:
        - TZ=Asia/Shanghai
        - RABBITMQ_DEFAULT_USER=root   #自定义登录账号
        - RABBITMQ_DEFAULT_PASS=123456 #自定义登录密码
        - RABBITMQ_ERLANG_COOKIE='secret_cookie'
      ports:
        - "15674:15672"
        - "5674:5672"
      depends_on:
          - rabbitmq01
      volumes:
        - ./rabbitmq/mq3/data:/var/lib/rabbitmq
        - ./rabbitmq/mq3/conf:/etc/rabbitmq
      command:  bash -c "sleep 10; rabbitmq-server;"
      networks:
        caseor_bridge:
            ipv4_address: 172.0.10.13

# 开启web管理 
# rabbitmq-plugins enable rabbitmq_management 

# # 加入rabbitmq集群

# # rabbit1
# rabbitmqctl stop_app
# rabbitmqctl reset
# rabbitmqctl start_app

# # rabbit2
# rabbitmqctl stop_app
# rabbitmqctl reset
# rabbitmqctl join_cluster --ram rabbit@rabbit1
# rabbitmqctl start_app

# # rabbit3
# rabbitmqctl stop_app
# rabbitmqctl reset
# rabbitmqctl join_cluster --ram rabbit@rabbit1
# rabbitmqctl start_app

View Code

使用docker启动mysql

复制代码
    mysql:
        container_name: mysql
        image: mysql
        privileged: true
        command: --character-set-server=utf8mb4 --collation-server=utf8mb4_general_ci --max_connections=2000 --max_allowed_packet=64M
        environment:
          - TZ=Asia/Shanghai
          - MYSQL_ROOT_PASSWORD=123456
        volumes:
          - ./mysql:/var/lib/mysql
        ports:
          - "3306:3306"
        healthcheck:
          test: [ "CMD", "mysqladmin" ,"ping", "-h", "localhost" ]
          interval: 5s
          timeout: 10s
          retries: 10
        networks:
          caseor_bridge:
            ipv4_address: 172.0.10.3

View Code

在数据库创建nacos数据库

复制代码
https://github.com/alibaba/nacos/blob/master/config/src/main/resources/META-INF/nacos-db.sql

准备三个nacos

复制代码
    nacos1:
        container_name: nacos1
        hostname: nacos1
        image: nacos/nacos-server
        environment:
            - MODE=cluster
            - PREFER_HOST_MODE=hostname
            - NACOS_SERVERS=nacos1:8848 nacos2:8848 nacos3:8848
            - SPRING_DATASOURCE_PLATFORM=mysql
            - MYSQL_SERVICE_HOST=172.0.10.3
            - MYSQL_SERVICE_PORT=3306
            - MYSQL_SERVICE_USER=root
            - MYSQL_SERVICE_PASSWORD=123456
            - MYSQL_SERVICE_DB_NAME=nacos
            - MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true  
            - JVM_XMS=128m
            - JVM_XMX=128m
            - JVM_XMN=128m
        volumes: 
            - ./nacos/cluster-logs/nacos1:/home/nacos/logs
            - ./nacos/init.d:/home/nacos/init.d
        ports: 
            - 8850:8848
            - 7850:7848     
            - 9870:9848
            - 9852:9849
        depends_on:
          - mysql
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.5

    nacos2:
        container_name: nacos2
        hostname: nacos2
        image: nacos/nacos-server
        environment:             
            - MODE=cluster
            - PREFER_HOST_MODE=hostname
            - NACOS_SERVERS=nacos1:8848 nacos2:8848 nacos3:8848
            - SPRING_DATASOURCE_PLATFORM=mysql
            - MYSQL_SERVICE_HOST=172.0.10.3
            - MYSQL_SERVICE_PORT=3306
            - MYSQL_SERVICE_USER=root
            - MYSQL_SERVICE_PASSWORD=123456
            - MYSQL_SERVICE_DB_NAME=nacos
            - MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true  
            - JVM_XMS=128m
            - JVM_XMX=128m
            - JVM_XMN=128m
        volumes: 
            - ./nacos/cluster-logs/nacos2:/home/nacos/logs
            - ./nacos/init.d:/home/nacos/init.d
        ports: 
            - 8849:8848
            - 7849:7848     
            - 9869:9848
            - 9851:9849
        depends_on:
          - mysql
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.6

    nacos3:
        container_name: nacos3
        hostname: nacos3
        image: nacos/nacos-server
        environment:             
            - MODE=cluster
            - PREFER_HOST_MODE=hostname
            - NACOS_SERVERS=nacos1:8848 nacos2:8848 nacos3:8848
            - SPRING_DATASOURCE_PLATFORM=mysql
            - MYSQL_SERVICE_HOST=172.0.10.3
            - MYSQL_SERVICE_PORT=3306
            - MYSQL_SERVICE_USER=root
            - MYSQL_SERVICE_PASSWORD=123456
            - MYSQL_SERVICE_DB_NAME=nacos
            - MYSQL_SERVICE_DB_PARAM=characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true  
            - JVM_XMS=128m
            - JVM_XMX=128m
            - JVM_XMN=128m
        volumes: 
            - ./nacos/cluster-logs/nacos3:/home/nacos/logs
            - ./nacos/init.d:/home/nacos/init.d
        ports: 
            - 8848:8848
            - 7848:7848     
            - 9848:9848
            - 9849:9849
        depends_on:
          - mysql
        networks:
          caseor_bridge:
                ipv4_address: 172.0.10.7

具体配置可以参考官网

查看nacos 控制台 http://127.0.0.1:8848/nacos/http://127.0.0.1:8849/nacos/http://127.0.0.1:8850/nacos/

可以看到集群已经搭建完成了

在.net core中使用nacos

https://github.com/nacos-group/nacos-sdk-csharp

复制代码
nacos-sdk-csharp.AspNetCore
nacos-sdk-csharp.Extensions.Configuration

在appsettings.json中新增Nacos配置

复制代码
  "Nacos": {
    "ServerAddresses": [ "http://192.168.110.39:8848" ],
    //命名空间GUID,public默认没有
    "Namespace": "779857e5-b517-437c-9026-f04c98d4bac1",
    // 配置中心
    "Listeners": [
      {
        "Group": "DEFAULT_GROUP",
        "DataId": "appsettings.json",
        "Optional": false
      }
    ],
    // 服务发现
    "ServiceName": "saas-system",
    "GroupName": "DEFAULT_GROUP"
  }

在program下新增

复制代码
//读取nacos配置文件
builder.Host.UseNacosConfig("Nacos");
//注册服务到nacos
builder.Services.AddNacosAspNet(builder.Configuration, "Nacos");

在program下继续读取appsettings的配置信息,首选需要在nacos上的appsettings配置信息

启动该服务

复制代码
dotnet run --urls=http://*:8083
dotnet run --urls=http://*:8084
dotnet run --urls=http://*:8085

在其他服务中调用当前服务接口

复制代码
 [HttpGet("nacos.test")]
 public async Task<IActionResult> TestNacos()
 {
     var instance= await _namingService.SelectOneHealthyInstance("saas-system", "DEFAULT_GROUP");
     var host = $"{instance.Ip}:{instance.Port}";

     var baseUrl = instance.Metadata.TryGetValue("secure", out _)
         ? $"https://{host}"
         : $"http://{host}";

     var url = $"{baseUrl}/system/tenant.package.query.list";

     using HttpClient client = new();
     var result = await client.GetAsync(url);
     return Ok(await result.Content.ReadAsStringAsync());

 }