etcd簡介
etcd是CoreOS團隊于2013年6月發起的開源專案,它的目標是構建一個高可用的分布式鍵值(key-value)資料庫,etcd內部采用raft協議作為一致性演算法,etcd基于Go語言實作,
etcd作為服務發現系統,有以下的特點:
- 簡單:安裝配置簡單,而且提供了HTTP API進行互動,使用也很簡單
- 安全:支持SSL證書驗證
- 快速:根據官方提供的benchmark資料,單實體支持每秒2k+讀操作
- 可靠:采用raft演算法,實作分布式系統資料的可用性和一致性
etcd專案地址:https://github.com/etcd-io/etcd
etcd應用場景
etcd比較多的應用場景是用于服務發現,服務發現(Service Discovery)要解決的是分布式系統中最常見的問題之一,即在同一個分布式集群中的行程或服務如何才能找到對方并建立連接,
從本質上說,服務發現就是要了解集群中是否有行程在監聽upd或者tcp埠,并且通過名字就可以進行查找和鏈接,
要解決服務發現的問題,需要下面三大支柱,缺一不可,
- 一個強一致性、高可用的服務存盤目錄,
基于Ralf演算法的etcd天生就是這樣一個強一致性、高可用的服務存盤目錄,
- 一種注冊服務和健康服務健康狀況的機制,
用戶可以在etcd中注冊服務,并且對注冊的服務配置key TTL,定時保持服務的心跳以達到監控健康狀態的效果,
- 一種查找和連接服務的機制,
etcd 安裝包的下載地址
etcd地址:https://github.com/etcd-io/etcd/releases
選擇對應的版本下載即可,Windows版本解壓后檔案目錄如下:

etcd是服務端,etcdctl 是內置客戶端
查看版本號 etcdctl --version

建議API version的版本設為3
windows下設定版本,使用: set ETCDCTL_API=3
etcdctl help查看版本3和2命令和功能方面有不少的差別





etcdctl的V3版本查看所有的keys,指令為:
etcdctl get "" --prefix --keys-only



在同級目錄分別創建如下三個啟動腳本:
默認使用2379埠提供HTTP API服務,2380埠和peer通信,
start01.bat
.\etcd.exe --name etcd01 ^
--data-dir .\data\etcd01 ^
--advertise-client-urls http://127.0.0.1:2379 ^
--listen-client-urls http://127.0.0.1:2379 ^
--listen-peer-urls http://127.0.0.1:2380 ^
--initial-advertise-peer-urls http://127.0.0.1:2380 ^
--initial-cluster-token etcd-cluster-1 ^
--initial-cluster etcd01=http://127.0.0.1:2380,etcd02=http://127.0.0.1:2381,etcd03=http://127.0.0.1:2382 ^
--initial-cluster-state new
pause
start02.bat
.\etcd.exe --name etcd02 ^
--data-dir .\data\etcd02 ^
--advertise-client-urls http://127.0.0.1:3379 ^
--listen-client-urls http://127.0.0.1:3379 ^
--listen-peer-urls http://127.0.0.1:2381 ^
--initial-advertise-peer-urls http://127.0.0.1:2381 ^
--initial-cluster-token etcd-cluster-1 ^
--initial-cluster etcd01=http://127.0.0.1:2380,etcd02=http://127.0.0.1:2381,etcd03=http://127.0.0.1:2382 ^
--initial-cluster-state new
pause
start03.bat
.\etcd.exe --name etcd03 ^
--data-dir .\data\etcd03 ^
--advertise-client-urls http://127.0.0.1:4379 ^
--listen-client-urls http://127.0.0.1:4379 ^
--listen-peer-urls http://127.0.0.1:2382 ^
--initial-advertise-peer-urls http://127.0.0.1:2382 ^
--initial-cluster-token etcd-cluster-1 ^
--initial-cluster etcd01=http://127.0.0.1:2380,etcd02=http://127.0.0.1:2381,etcd03=http://127.0.0.1:2382 ^
--initial-cluster-state new
pause
然后在同級目錄下創建好對應的data-dir,如/data/etcd01、/data/etcd02、/data/etcd03,不創建也行,啟動后會自動創建,
依次啟動start01.bat、start02.bat、start03.bat三個腳本,然后使用etcdctl.exe member list,當輸出如下資訊時,代表集群創建成功了,
etcd集群啟動引數說明
| 引數 | 使用說明 |
|
|---|---|---|
| --name etcd0 | 本member的名字 | |
| --initial-advertise-peer-urls http://192.168.2.55:2380 | 其他member使用,其他member通過該地址與本member互動資訊,一定要保證從其他member能可訪問該地址,靜態配置方式下,該引數的value一定要同時在--initial-cluster引數中存在, memberID的生成受--initial-cluster-token和--initial-advertise-peer-urls影響, | |
| --listen-peer-urls http://0.0.0.0:2380 | 本member側使用,用于監聽其他member發送資訊的地址,ip為全0代表監聽本member側所有介面 | |
| --listen-client-urls http://0.0.0.0:2379 | 本member側使用,用于監聽etcd客戶發送資訊的地址,ip為全0代表監聽本member側所有介面 | |
| --advertise-client-urls http://192.168.2.55:2379 | etcd客戶使用,客戶通過該地址與本member互動資訊,一定要保證從客戶側能可訪問該地址 | |
| --initial-cluster-token etcd-cluster-2 | 用于區分不同集群,本地如有多個集群要設為不同, | |
| --initial-cluster etcd0=http://192.168.2.55:2380, etcd1=http://192.168.2.54:2380 ,etcd2=http://192.168.2.56:2380 | 本member側使用,描述集群中所有節點的資訊,本member根據此資訊去聯系其他member, memberID的生成受--initial-cluster-token和--initial-advertise-peer-urls影響, | |
| --initial-cluster-state new | 用于指示本次是否為新建集群,有兩個取值new和existing,如果填為existing,則該member啟動時會嘗試與其他member互動, 集群初次建立時,要填為new,經嘗試最后一個節點填existing也正常,其他節點不能填為existing, 集群運行程序中,一個member故障后恢復時填為existing,經嘗試填為new也正常, | |
| -data-dir | 指定節點的資料存盤目錄,這些資料包括節點ID,集群ID,集群初始化配置,Snapshot檔案,若未指定-wal-dir,還會存盤WAL檔案;如果不指定會用預設目錄, |
|
| -discovery http://192.168.1.163:20003/v2/keys/discovery/78b12ad7-2c1d-40db-9416-3727baf686cb | 用于自發現模式下,指定第三方etcd上key地址,要建立的集群各member都會向其注冊自己的地址, |
- —data-dir 指定節點的資料存盤目錄,這些資料包括節點ID,集群ID,集群初始化配置,Snapshot檔案,若未指定—wal-dir,還會存盤WAL檔案;
- —wal-dir 指定節點的was檔案的存盤目錄,若指定了該引數,wal檔案會和其他資料檔案分開存盤,
- —name 節點名稱
- —initial-advertise-peer-urls 告知集群其他節點url.
- — listen-peer-urls 監聽URL,用于與其他節點通訊
- — advertise-client-urls 告知客戶端url, 也就是服務的url
- — initial-cluster-token 集群的ID
- — initial-cluster 集群中所有節點
檢查etcd服務串列
使用 etcdctl.exe member list 命令查看集群串列:
D:\etcd\etcd-v3.3.25-windows-amd64>etcdctl.exe member list
19ac17627e3e396f: name=etcd03 peerURLs=http://127.0.0.1:2382 clientURLs=http://127.0.0.1:4379 isLeader=false
bf9071f4639c75cc: name=etcd01 peerURLs=http://127.0.0.1:2380 clientURLs=http://127.0.0.1:2379 isLeader=true
e7b968b9fb1bc003: name=etcd02 peerURLs=http://127.0.0.1:2381 clientURLs=http://127.0.0.1:3379 isLeader=false
如果出現如下的資訊,代表可能etcd啟動程序阻塞住了,只要在cmd視窗里按下回車鍵就ok了
D:\etcd\etcd-v3.3.25-windows-amd64>etcdctl.exe member list
client: etcd cluster is unavailable or misconfigured; error #0: dial tcp 127.0.0.1:4001: connectex: No connection could be made because the target machine actively refused it.
; error #1: client: endpoint http://127.0.0.1:2379 exceeded header timeout
或者使用curl訪問或網頁輸入查看http://127.0.0.1:2379/v2/members:
curl http://127.0.0.1:2379/v2/members
回傳以下結果(3個節點):
{
"members": [{
"id": "19ac17627e3e396f",
"name": "etcd03",
"peerURLs": ["http://127.0.0.1:2382"],
"clientURLs": []
}, {
"id": "bf9071f4639c75cc",
"name": "etcd01",
"peerURLs": ["http://127.0.0.1:2380"],
"clientURLs": ["http://127.0.0.1:2379"]
}, {
"id": "e7b968b9fb1bc003",
"name": "etcd02",
"peerURLs": ["http://127.0.0.1:2381"],
"clientURLs": ["http://127.0.0.1:3379"]
}]
}
在任意節點執行健康檢查,查看集群狀態:
(注:僅etcdctl 有v2和v3兩種api,注意區別),關于v3 api的用法,參見etcdctl的使用[v3版本]:https://blog.csdn.net/huwh_/article/details/80225902
etcdctl cluster-health

etcd的go客戶端的簡單操作:
package main
import (
"context"
"fmt"
"time"
"github.com/coreos/etcd/clientv3"
)
func main() {
//客戶端配置
config := clientv3.Config{
Endpoints: []string{"127.0.0.1:2379"},
DialTimeout: 5 * time.Second,
}
//建立連接
client, err := clientv3.New(config)
defer client.Close()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("connect success")
//控制超時
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
//1. 增-存值
_, err = client.Put(ctx, "/demo/demo1_key", "demo1_value")
//操作完畢,cancel掉
cancel()
if err != nil {
fmt.Println("put failed, err:", err)
return
}
//2. 查-獲取值, 也設定超時
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
resp, err := client.Get(ctx, "/demo/demo1_key")
// Get查詢還可以增加WithPrefix選項,獲取某個目錄下的所有子元素
//eg: resp, err := client.Get(ctx, "/demo/", clientv3.WithPrefix())
cancel()
if err != nil {
fmt.Println("get failed err:", err)
return
}
for _, item := range resp.Kvs { //Kvs 回傳key的串列
fmt.Printf("%s : %s \n", item.Key, item.Value)
}
//3. 改-修改值
ctx, _ = context.WithTimeout(context.Background(), time.Second)
_,err = client.Put(ctx, "/demo/demo1_key", "update_value", clientv3.WithPrevKV())
if err != nil {
fmt.Println("get failed err: ", err)
}
//fmt.Println(string(resp.PrevKv.Value))
//4. 刪-洗掉值
ctx, _ = context.WithTimeout(context.Background(), time.Second)
_, err = client.Delete(ctx, "/demo/demo1_key")
if err != nil {
fmt.Println(err)
}
//fmt.Println(resp.PrevKvs)
}
zRPC的簡單使用
zRPC來自于最近比較火的一個微服務框架go-zero,go-zero是一個集成了各種工程實踐的包含了Web和RPC協議的功能完善的微服務框架,zRPC是其中的一個可獨立使用的模塊,
zRPC地址:https://github.com/tal-tech/go-zero/tree/master/zrpc
zRPC底層依賴gRPC,內置了服務注冊、負載均衡、攔截器等模塊,其中還包括自適應降載,自適應熔斷,限流等微服務治理方案,是一個簡單易用的可直接用于生產的企業級RPC框架,
zRPC支持直連和基于etcd服務發現兩種方式,我們以基于etcd做服務發現為例演示zRPC的基本使用:
配置
創建hello.yaml組態檔,配置如下:
Name: hello.rpc // 服務名
ListenOn: 127.0.0.1:9090 // 服務監聽地址
Etcd:
Hosts:
- 127.0.0.1:2379 // etcd服務地址
Key: hello.rpc // 服務注冊key
注意檔案編碼必須為utf-8,格式也要正確,
創建hello.proto檔案,并生成對應的go代碼,
生成go代碼:
protoc --go_out=plugins=grpc:. hello.proto

protoc的安裝,https://github.com/protocolbuffers/protobuf/releases
從 Protobuf Releases 下載最先版本的發布包安裝即可,可放到go的bin目錄內全域使用,
下載protobuf編譯器所需插件
用git下載protoc在go下運行所需插件(執行): go get github.com/golang/protobuf(gopath的bin目錄會生成protoc-gen-go.exe)
proto檔案標量型別
| proto型別 | go型別 | 備注 | proto型別 | go型別 | 備注 |
|---|---|---|---|---|---|
| double | float64 | float | float32 | ||
| int32 | int32 | int64 | int64 | ||
| uint32 | uint32 | uint64 | uint64 | ||
| sint32 | int32 | 適合負數 | sint64 | int64 | 適合負數 |
| fixed32 | uint32 | 固長編碼,適合大于2^28的值 | fixed64 | uint64 | 固長編碼,適合大于2^56的值 |
| sfixed32 | int32 | 固長編碼 | sfixed64 | int64 | 固長編碼 |
| bool | bool | string | string | UTF8 編碼,長度不超過 2^32 | |
| bytes | []byte | 任意位元組序列,長度不超過 2^32 |
標量型別如果沒有被賦值,則不會被序列化,決議時,會賦予默認值,
- strings:空字串
- bytes:空序列
- bools:false
- 數值型別:0
簡單示例:

syntax = "proto3";
package pb;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
服務端:
Server端代碼:
package main
import (
"context"
"flag"
"log"
"testzrpc/msgs/zrpc/pb"
"github.com/tal-tech/go-zero/core/conf"
"github.com/tal-tech/go-zero/zrpc"
"google.golang.org/grpc"
)
type Config struct {
zrpc.RpcServerConf
}
var cfgFile = flag.String("f", "./hello.yaml", "cfg file")
func main() {
flag.Parse()
var cfg Config
conf.MustLoad(*cfgFile, &cfg)
srv, err := zrpc.NewServer(cfg.RpcServerConf, func(s *grpc.Server) {
pb.RegisterGreeterServer(s, &Hello{})
})
if err != nil {
log.Fatal(err)
}
srv.Start()
}
type Hello struct{}
func (h *Hello) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "server say,hello " + in.Name}, nil
}
需要注意的是:
需要更改下go.mod檔案中的grpc版本號,默認最新的1.34,啟動服務端會報錯的,可改為使用v1.29.1
etcd/clientv3庫跟最新的grpc版本不兼容,需要降低 grpc 版本,如1.26.0,

客戶端:
package main
import (
"context"
"log"
"testzrpc/msgs/zrpc/pb"
"github.com/tal-tech/go-zero/core/discov"
"github.com/tal-tech/go-zero/zrpc"
)
func main() {
client := zrpc.MustNewClient(zrpc.RpcClientConf{
Etcd: discov.EtcdConf{
Hosts: []string{"127.0.0.1:2379"},
Key: "hello.rpc",
},
})
conn := client.Conn()
hello := pb.NewGreeterClient(conn)
reply, err := hello.SayHello(context.Background(), &pb.HelloRequest{Name: "go-zero aaaa"})
if err != nil {
log.Fatal(err)
}
log.Println(reply.Message)
}
多個微服務如何使用?如何實作負載均衡和容災,做個試驗,把server.go復制一份,改為server1.go,
把hello.yaml復制一份改為hello1.yaml,改hello1.yaml中的ListenOn,埠變為9091,這時候把server.go和server1.go同時運行起來,看一下:

此時,運行下客戶端,發現輸出為:

再把server1.go服務停掉,運行下客戶端試試輸出為:

綜上,使用zRPC挺簡單的,并且zRPC內置了服務注冊、負載均衡、攔截器等模塊,
其中還包括自適應降載,自適應熔斷,限流等微服務治理方案,是一個簡單易用的可直接用于生產的企業級RPC框架,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/263880.html
標籤:區塊鏈
上一篇:2021新加坡智能公鏈KOC發展規劃,“吃豆人”滿血沖刺
下一篇:flutter繪制柱狀圖和折線圖
