搭建本地集群

为测试和开发配置本地集群

对于测试和开发部署,最快且最简单的方法是配置一个本地集群。对于生产环境部署,请参考 集群 部分。

本地独立集群

启动集群

运行以下命令将 etcd 集群作为独立集群进行部署:

$ ./etcd
...

如果当前工作目录中没有 etcd 二进制文件,它可能位于 $GOPATH/bin/etcd/usr/local/bin/etcd。请根据实际情况运行相应命令。

运行中的 etcd 成员会在 localhost:2379 监听客户端请求。

与集群交互

使用 etcdctl 与运行中的集群进行交互:

  1. 在集群中存储一个示例键值对:

      $ ./etcdctl put foo bar
      OK
    

    如果输出了 OK,则表示键值对存储成功。

  2. 检索 foo 的值:

    $ ./etcdctl get foo
    bar
    

    如果返回了 bar,则说明与 etcd 集群的交互正常。

本地多成员集群

启动集群

etcd Git 仓库根目录下提供了一个 Procfile,可轻松配置本地多成员集群。要启动一个多成员集群,请进入 etcd 源码树的根目录并执行以下操作:

  1. 安装 goreman 以控制基于 Procfile 的应用程序:

    $ go install github.com/mattn/goreman@latest
    
  2. 使用 etcd 提供的默认 Procfile 通过 goreman 启动集群:

    $ goreman -f Procfile start
    

    成员将开始运行。它们分别在 localhost:2379localhost:22379localhost:32379 监听客户端请求。

与集群交互

使用 etcdctl 与运行中的集群进行交互:

  1. 打印成员列表:

    $ etcdctl --write-out=table --endpoints=localhost:2379 member list
    

    etcd 成员列表将如下所示:

    +------------------+---------+--------+------------------------+------------------------+
    |        ID        | STATUS  |  NAME  |       PEER ADDRS       |      CLIENT ADDRS      |
    +------------------+---------+--------+------------------------+------------------------+
    | 8211f1d0f64f3269 | started | infra1 | http://127.0.0.1:2380  | http://127.0.0.1:2379  |
    | 91bc3c398fb3c146 | started | infra2 | http://127.0.0.1:22380 | http://127.0.0.1:22379 |
    | fd422379fda50e48 | started | infra3 | http://127.0.0.1:32380 | http://127.0.0.1:32379 |
    +------------------+---------+--------+------------------------+------------------------+
    
  2. 在集群中存储一个示例键值对:

    $ etcdctl put foo bar
    OK
    

    如果输出了 OK,则表示键值对存储成功。

测试容错能力

为了测试 etcd 的容错能力,终止一个成员并尝试获取键值。

  1. 确定要停止的成员的进程名称。

    Procfile 列出了多成员集群的属性。例如,考虑进程名为 etcd2 的成员。

  2. 停止该成员:

    # kill etcd2
    $ goreman run stop etcd2
    
  3. 存储一个键:

    $ etcdctl put key hello
    OK
    
  4. 检索上一步中存储的键:

    $ etcdctl get key
    hello
    
  5. 从已停止的成员中检索键:

    $ etcdctl --endpoints=localhost:22379 get key
    

    该命令应显示由连接失败引起的错误:

    2017/06/18 23:07:35 grpc: Conn.resetTransport failed to create client transport: connection error: desc = "transport: dial tcp 127.0.0.1:22379: getsockopt: connection refused"; Reconnecting to "localhost:22379"
    Error:  grpc: timed out trying to connect
    
  6. 重新启动已停止的成员:

    $ goreman run restart etcd2
    
  7. 从重新启动的成员中获取键:

    $ etcdctl --endpoints=localhost:22379 get key
    hello
    

    重启成员将重新建立连接。etcdctl 现在能够成功检索该键。要了解更多关于与 etcd 交互的信息,请阅读 与 etcd 交互章节


最后更新于 2025 年 6 月 3 日:递归地将 v3.6 的内容复制到 v3.7(a90b2a6)