zoukankan      html  css  js  c++  java
  • consul配置和使用

    一:consul介绍#

    consul用于提供服务发现和服务配置的工具。有以下特性:
    1. 服务发现
    consul的客户端提供一个服务,比如api或者mysql,另外一个客户端就可以去发现指定服务的服务提供者。通过DNS或者HTTP应用程序可以容易找到所依赖的服务
    2. 健康检查
    consul 可以提供健康检查服务(比如:webserver是否返回了200 ok状态码)或者使用本地节点(比如:内存使用大于90%)。这个信息可以监视集群的健康。可以用来避免将流量发送到不健康的主机
    3.key/value 存储
    应用程序可以使用consul的层级的key/value存储,比如动态配置,协调服务。直接可以用HTTP API来操作
    4.多数据中心
    consul支持开箱即用的多数据中心。

    二:consul安装配置#

    consul的安装非常容易,直接到 https://www.consul.io/downloads.html 下载你所在平台的安装包,可以直接下载二进制包, 然后unzip解压,会得到一个 consul 的文件,然后把它 cp 到/usr/local/bin 目录下
    验证安装:在终端下直接输入 consul ,输出下面的内容说明安装成功

    复制代码
    Usage: consul [--version] [--help] <command> [<args>]
    

    Available commands are:
    agent Runs a Consul agent
    catalog Interact with the catalog
    connect Interact with Consul Connect
    event Fire a new event
    exec Executes a command on Consul nodes
    force
    -leave Forces a member of the cluster to enter the "left" state
    info Provides debugging information
    for operators.
    intention Interact with Connect service intentions
    join Tell Consul agent to join cluster
    keygen Generates a
    new encryption key
    keyring Manages gossip layer encryption keys
    kv Interact with the key
    -value store
    leave Gracefully leaves the Consul cluster and shuts down
    lock Execute a command holding a lock
    maint Controls node or service maintenance mode
    members Lists the members of a Consul cluster
    monitor Stream logs
    from a Consul agent
    operator Provides cluster-level tools for Consul operators
    reload Triggers the agent to reload configuration files
    rtt Estimates network round trip time between nodes
    snapshot Saves, restores and inspects snapshots of Consul server state
    validate Validate config files
    /directories
    version Prints the Consul version
    watch Watch
    for changes in Consul

    复制代码

    三:consul启动#

    完成consul的安装后,必须运行agent. agent可以运行为 server 或者 client模式。还有个开发模式dev。 每个数据中心至少必须拥有一台server。建议在一个集群中有3或者5个server。部署单一server,在出现失败时,会不可避免的出现数据丢失。

    以dev模式启动consul
    还有一个特殊的运行模式 -dev的模式,命令如下
    ./consul agent -dev
    说明:
    -dev 表示开发模式运行,默认客户端地址是在127.0.0.1 上
    -dev(该节点的启动不能用于生产环境,因为该模式下不会持久化任何状态),该启动模式仅仅是为了快速便捷的启动单节点consul

    以server模式启动consul
    consul agent -server -bind=192.168.0.109 -data-dir=/etc/consul.d
    其实没有 -server,默认就是以client模式启动的

    以client模式启动consul
    consul agent -client=0.0.0.0 -bind=192.168.0.109 -data-dir=/etc/consul.d

    四:consul的常用命令#

    https://www.consul.io/docs/commands/index.html  官方命令大全地址

    consul常用命令+常用选项
    agent
    作用:运行一个consul agent


    join
    作用:将agent加入到consul cluster


    members
    作用:列出consul cluster集群中的members


    常用选项option:
    -data-dir
    作用:指定agent储存状态的数据目录
    这是所有agent都必须的
    对于server尤其重要,因为他们必须持久化集群的状态


    -config-dir
    作用:指定service的配置文件和检查定义所在的位置
    通常会指定为"某一个路径/consul.d"(通常情况下,.d表示一系列配置文件存放的目录)


    -config-file
    作用:指定一个要装载的配置文件
    该选项可以配置多次,进而配置多个配置文件(后边的会合并前边的,相同的值覆盖)


    -dev
    作用:创建一个开发环境下的server节点
    该参数配置下,不会有任何持久化操作,即不会有任何数据写入到磁盘
    这种模式不能用于生产环境(因为第二条)


    -bootstrap-expect
    作用:该命令通知consul server我们现在准备加入的server节点个数,该参数是为了延迟日志复制的启动直到我们指定数量的server节点成功的加入后启动。


    -node
    作用:指定节点在集群中的名称
    该名称在集群中必须是唯一的(默认采用机器的host)
    推荐:直接采用机器的IP


    -bind
    作用:指明节点的IP地址


    -server
    作用:指定节点为server
    每个数据中心(DC)的server数推荐为3或5(理想的是,最多不要超过5)
    所有的server都采用raft一致性算法来确保事务的一致性和线性化,事务修改了集群的状态,且集群的状态保存在每一台server上保证可用性
    server也是与其他DC交互的门面(gateway)


    -client
    作用:指定节点为client
    若不指定为-server,其实就是-client


    -join
    作用:将节点加入到集群


    -domain
    -dc
    作用:指定机器加入到哪一个dc中

    查看consul的命令 ./consul

    复制代码
    # ./consul
    Usage: consul [
    --version] [--help] <command> [<args>]

    Available commands are:
    acl Interact with Consul's ACLs
    agent Runs a Consul agent
    catalog Interact with the catalog
    connect Interact with Consul Connect
    debug Records a debugging archive
    for operators
    event Fire a new event
    exec Executes a command on Consul nodes
    force
    -leave Forces a member of the cluster to enter the "left" state
    info Provides debugging information
    for operators.
    intention Interact with Connect service intentions
    join Tell Consul agent to join cluster
    keygen Generates a
    new encryption key
    keyring Manages gossip layer encryption keys
    kv Interact with the key
    -value store
    leave Gracefully leaves the Consul cluster and shuts down
    lock Execute a command holding a lock
    maint Controls node or service maintenance mode
    members Lists the members of a Consul cluster
    monitor Stream logs
    from a Consul agent
    operator Provides cluster-level tools for Consul operators
    reload Triggers the agent to reload configuration files
    rtt Estimates network round trip time between nodes
    services Interact with services
    snapshot Saves, restores and inspects snapshots of Consul server state
    tls Builtin helpers
    for creating CAs and certificates
    validate Validate config files
    /directories
    version Prints the Consul version
    watch Watch
    for changes in Consul

    复制代码

    查看某一个子命令的使用方法

    比如查看 catalog 的使用方法,使用下面的命令:

    ./consul catalog help

    复制代码
    Usage: consul catalog <subcommand> [options] [args]
    

    This command has subcommands for interacting with Consul's catalog. The
    catalog should not be confused with the agent, although the APIs and
    responses may be similar.

    Here are some simple examples, and more detailed examples are available
    in the subcommands or the documentation.

    List all datacenters:

      $ consul catalog datacenters
    

    List all nodes:

      $ consul catalog nodes
    

    List all services:

      $ consul catalog services
    

    For more examples, ask for subcommand help or view the documentation.

    Subcommands:
    datacenters Lists all known datacenters
    nodes Lists all nodes in the given datacenter
    services Lists all registered services in a datacenter

    复制代码

    查看组成consul服务的node各种命令

    a: 命令行查询

    [root@localhost]# ./consul catalog nodes
    Node                          ID             Address           DC
    localhost.localdomain  901b6ebb  192.168.0.109  dc1

    b: http接口查询,用 curl 来查询

    复制代码
    [root@localhost ]# curl localhost:8500/v1/catalog/nodes | python -m json.tool
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   256  100   256    0     0  15280      0 --:--:-- --:--:-- --:--:-- 16000
    [
        {
            "Address": "192.168.0.109",
            "CreateIndex": 5,
            "Datacenter": "dc1",
            "ID": "901b6ebb-8a9b-1930-62e2-65a264ff0fd1",
            "Meta": {
                "consul-network-segment": ""
            },
            "ModifyIndex": 6,
            "Node": "localhost.localdomain",
            "TaggedAddresses": {
                "lan": "192.168.0.109",
                "wan": "192.168.0.109"
            }
        }
    ]
    复制代码

    c: 通过dns查询成员node的地址,默认后缀是 node.consul

    复制代码
    root@localhost]# dig @127.0.0.1 -p 8600 192.168.0.109.node.cosul
    

    ; <<>> DiG 9.9.4-RedHat-9.9.4-61.el7 <<>> @127.0.0.1 -p 8600 192.168.0.109.node.cosul
    ; (
    1 server found)
    ;; global options:
    +cmd
    ;; Got answer:
    ;;
    ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 51942
    ;; flags: qr rd; QUERY:
    1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
    ;; WARNING: recursion requested but not available

    ;; QUESTION SECTION:
    ;192.168.0.109.node.cosul. IN A

    ;; Query time: 0 msec
    ;; SERVER:
    127.0.0.1#8600(127.0.0.1)
    ;; MSG SIZE rcvd:
    42

    复制代码

    五:添加,查询服务:(服务注册,服务发现)#

    下面我们以dev的模式启动consul#

    5.1 添加一个服务(也叫 服务注册

    1. 新建一个文件夹 mkdir /etc/consul.d
    2. 写入一个json格式信息到 /etc/consul.d/web.json 文件中
    echo '{"service": {"name": "web", "tags": ["rails"], "port": 80}}' | sudo tee /etc/consul.d/web.json
    3. 重新启动 cosul
    consul agent -dev -config-dir=/etc/consul.d

    或者通过 api 来注册服务, api是:agent/service:

    1. 先编写一个json文件,把它命名为web2.json

    vi web2.json

    复制代码
    {
        "Name": "web2",
        "Tags": [
            "rails"
        ],
        "Address": "",
        "Port": 81,
        "ServiceEnableTagOverride": false
    }
    复制代码

    2. 然后用curl命令把这个json文件通过http接口写入到consul里

    curl --request PUT --data @web2.json http://127.0.0.1:8500/v1/agent/service/register

    查询刚才注册的服务, 看看服务是否注册成功

    [root@localhost]# ./consul catalog services
    consul
    web2

    5.2 查询定义服务 (也叫 服务发现
    第一:通过DNS来查询

     我们可以用DNS API 来查询服务,服务名默认为: NAME.service.consul

    eg1: 查询名字为 web 的服务
    dig @127.0.0.1 -p 8600 web.service.consul

    复制代码
    ; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4096
    ;; QUESTION SECTION:
    ;web.service.consul.    IN    A
    

    ;; ANSWER SECTION:
    web.service.consul. 0 IN A 127.0.0.1

    复制代码

    eg2: 查询名字为 web2 的服务

    查询类型要指定为为srv,才能看到服务端口.  我们来查询web2服务

    复制代码
    [root@localhost]# dig @127.0.0.1 -p 8600 web2.service.consul srv
    

    ; <<>> DiG 9.9.4-RedHat-9.9.4-61.el7 <<>> @127.0.0.1 -p 8600 web2.service.consul srv
    ; (
    1 server found)
    ;; global options:
    +cmd
    ;; Got answer:
    ;;
    ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 43040
    ;; flags: qr aa rd; QUERY:
    1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 3
    ;; WARNING: recursion requested but not available

    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4096
    ;; QUESTION SECTION:
    ;web2.service.consul. IN SRV

    ;; ANSWER SECTION:
    web2.service.consul. 0 IN SRV 1 1 81 localhost.localdomain.node.dc1.consul.

    ;; ADDITIONAL SECTION:
    localhost.localdomain.node.dc1.consul. 0 IN A 192.168.0.109
    localhost.localdomain.node.dc1.consul.
    0 IN TXT "consul-network-segment="

    ;; Query time: 0 msec
    ;; SERVER:
    127.0.0.1#8600(127.0.0.1)
    ;; MSG SIZE rcvd:
    157

    复制代码

    第二:通过http接口查询

    也可以用HTTP API来查询服务

    eg1: 查询 web 服务
    curl http://localhost:8500/v1/catalog/service/web | python -m json.tool

    复制代码
    [
    
    {
        "ID": "5901c710-c6c4-f8f8-a9eb-77e76e39f034", 
        "Node": "localhost.localdomain", 
        "Address": "127.0.0.1", 
        "Datacenter": "dc1", 
        "TaggedAddresses": {
            "lan": "127.0.0.1", 
            "wan": "127.0.0.1"
        }, 
        "NodeMeta": {
            "consul-network-segment": ""
        }, 
        "ServiceKind": "", 
        "ServiceID": "web", 
        "ServiceName": "web", 
        "ServiceTags": [
            "rails"
        ], 
        "ServiceAddress": "", 
        "ServiceMeta": { }, 
        "ServicePort": 80, 
        "ServiceEnableTagOverride": false, 
        "ServiceProxyDestination": "", 
        "ServiceConnect": {
            "Native": false, 
            "Proxy": null
        }, 
        "CreateIndex": 10, 
        "ModifyIndex": 10
    }
    ]
    复制代码

    eg2:查询web2服务

    curl 命令后面的  python -m json.tool 是格式化返回的json,不然返回就是一串字符串,不便于阅读

    复制代码
    [root@localhost]# curl http://127.0.0.1:8500/v1/catalog/service/web2 | python -m json.tool
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   542  100   542    0     0   394k      0 --:--:-- --:--:-- --:--:--  529k
    [
        {
            "Address": "192.168.0.109",
            "CreateIndex": 407,
            "Datacenter": "dc1",
            "ID": "901b6ebb-8a9b-1930-62e2-65a264ff0fd1",
            "ModifyIndex": 407,
            "Node": "localhost.localdomain",
            "NodeMeta": {
                "consul-network-segment": ""
            },
            "ServiceAddress": "",
            "ServiceConnect": {},
            "ServiceEnableTagOverride": false,
            "ServiceID": "web2",
            "ServiceKind": "",
            "ServiceMeta": {},
            "ServiceName": "web2",
            "ServicePort": 81,
            "ServiceProxy": {},
            "ServiceProxyDestination": "",
            "ServiceTags": [
                "rails"
            ],
            "ServiceWeights": {
                "Passing": 1,
                "Warning": 1
            },
            "TaggedAddresses": {
                "lan": "192.168.0.109",
                "wan": "192.168.0.109"
            }
        }
    ]
    复制代码

    5.3 查询服务健康状况
    curl http://localhost:8500/v1/health/service/web?passing

    复制代码
    [
    
    {
        "Node": {
            "ID": "5901c710-c6c4-f8f8-a9eb-77e76e39f034", 
            "Node": "localhost.localdomain", 
            "Address": "127.0.0.1", 
            "Datacenter": "dc1", 
            "TaggedAddresses": {
                "lan": "127.0.0.1", 
                "wan": "127.0.0.1"
            }, 
            "Meta": {
                "consul-network-segment": ""
            }, 
            "CreateIndex": 9, 
            "ModifyIndex": 10
        }, 
        "Service": {
            "ID": "web", 
            "Service": "web", 
            "Tags": [
                "rails"
            ], 
            "Address": "", 
            "Meta": null, 
            "Port": 80, 
            "EnableTagOverride": false, 
            "ProxyDestination": "", 
            "Connect": {
                "Native": false, 
                "Proxy": null
            }, 
            "CreateIndex": 10, 
            "ModifyIndex": 10
        }, 
        "Checks": [
            {
                "Node": "localhost.localdomain", 
                "CheckID": "serfHealth", 
                "Name": "Serf Health Status", 
                "Status": "passing", 
                "Notes": "", 
                "Output": "Agent alive and reachable", 
                "ServiceID": "", 
                "ServiceName": "", 
                "ServiceTags": [ ], 
                "Definition": { }, 
                "CreateIndex": 9, 
                "ModifyIndex": 9
            }
        ]
    }
    ]
    复制代码

    5.4 查询agent上所有的服务

    复制代码
    [root@localhost]# curl http://127.0.0.1:8500/v1/agent/services | python -m json.tool
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   298  100   298    0     0   171k      0 --:--:-- --:--:-- --:--:--  291k
    {
        "web": {
            "Address": "",
            "EnableTagOverride": false,
            "ID": "web",
            "Meta": {},
            "Port": 80,
            "Service": "web",
            "Tags": [
                "rails"
            ],
            "Weights": {
                "Passing": 1,
                "Warning": 1
            }
        },
        "web2": {
            "Address": "",
            "EnableTagOverride": false,
            "ID": "web2",
            "Meta": {},
            "Port": 81,
            "Service": "web2",
            "Tags": [
                "rails"
            ],
            "Weights": {
                "Passing": 1,
                "Warning": 1
            }
        }
    }
    复制代码

    六: 删除服务#

    删除名字为 web 的服务

    curl --request PUT  http://127.0.0.1:8500/v1/agent/service/deregister/web

    七: kv操作 #

    官方地址: https://www.consul.io/api/kv.html

    1. 写入一个名为 “key1” 的key, 值为 hello

    命令:

    curl -X PUT --data "hello" http://127.0.0.1:8500/v1/kv/key1

    2: 查询 key1:

    命令:

    复制代码
    # curl http://127.0.0.1:8500/v1/kv/key1 |python -m json.tool
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100    95  100    95    0     0  77614      0 --:--:-- --:--:-- --:--:-- 95000
    [
        {
            "CreateIndex": 601,
            "Flags": 0,
            "Key": "key1",
            "LockIndex": 0,
            "ModifyIndex": 601,
            "Value": "aGVsbG8="          //base64编码
        }
    ]
    复制代码

    3: 查询指定路径下的所有key:

    命令:

    # curl 127.0.0.1:8500/v1/kv/key1?keys
    ["key1"]

    4:删除key

    curl -X DELETE http://127.0.0.1:8500/v1/kv/key1

    八:查看consul中的每一个consul的节点信息#

    # consul members

    Node Address Status Type Build Protocol DC
    localhost.localdomain 127.0.0.1:8301 alive server 0.7.5 2 dc1

    说明:
    Address:节点地址
    Status:alive表示节点健康
    Type:server运行状态是server状态
    DC:dc1表示该节点属于DataCenter1
    members命令的输出是基于gossip协议的,并且是最终一致的(也就是说,某一个时刻你去运用该命令查到的consul节点的状态信息可能是有误的)

    参考:
    https://www.consul.io/intro/getting-started/agent.html
    https://www.consul.io/docs/index.html
    https://book-consul-guide.vnzmi.com/
    http://www.liangxiansen.cn/2017/04/06/consul/

    原文地址:https://www.cnblogs.com/jiujuan/p/9356772.html
  • 相关阅读:
    深入浅出计算机组成原理学习笔记:第三十七讲
    深入浅出计算机组成原理学习笔记:第三十九讲
    深入浅出计算机组成原理学习笔记:第三十八讲
    数据结构与算法之美学习笔记:第二十二讲
    深入浅出计算机组成原理学习笔记:第三十六讲
    深入浅出计算机组成原理学习笔记:第十七讲
    深入浅出计算机组成原理学习笔记:第三十五讲
    数据结构与算法之美学习笔记:第二十一讲
    数据结构与算法之美学习笔记:第二十讲
    数据结构与算法之美学习笔记:第十九讲
  • 原文地址:https://www.cnblogs.com/jpfss/p/11940960.html
Copyright © 2011-2022 走看看