1 Consul简介
Consul是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置。与其他分布式服务注册与发现的方案相比,Consul的方案更“一站式”,内置了服务注册与发现框 架、分布一致性协议实现、健康检查、Key/Value存储、多数据中心方案,不再需要依赖其他工具(比如ZooKeeper等)。使用起来也较 为简单。Consul用Golang实现,因此具有天然可移植性(支持Linux、windows和Mac OS X);安装包仅包含一个可执行文件,方便部署,与Docker等轻量级容器可无缝配合。
官网在
https://learn.hashicorp.com/consul
2 Consul安装和运行
下载地址https://www.consul.io/downloads.html
如MacOS下,直接下载zip包解压后放到/usr/local/bin/
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
开发模式运行agent
dotzdeMacBook-Pro-2:~ dotz$ consul agent -dev
==> Starting Consul agent...
==> Consul agent running!
Version: 'v1.4.3'
Node ID: '3ecdbc84-9f8e-ee75-33cd-e00d7f9443f2'
Node name: 'dotzdeMacBook-Pro-2.local'
Datacenter: 'dc1' (Segment: '<all>')
Server: true (Bootstrap: false)
Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, gRPC: 8502, DNS: 8600)
Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false
==> Log data will now stream in as it occurs:
2019/03/26 11:58:59 [DEBUG] agent: Using random ID "3ecdbc84-9f8e-ee75-33cd-e00d7f9443f2" as node ID
2019/03/26 11:58:59 [WARN] agent: Node name "dotzdeMacBook-Pro-2.local" will not be discoverable via DNS due to invalid characters. Valid characters include all alpha-numerics and dashes.
2019/03/26 11:58:59 [INFO] raft: Initial configuration (index=1): [{Suffrage:Voter ID:3ecdbc84-9f8e-ee75-33cd-e00d7f9443f2 Address:127.0.0.1:8300}]
通过http://127.0.0.1:8500/ui可以访问ui界面
3 客户端API
eg:
package main
import "github.com/hashicorp/consul/api"
import "fmt"
func main() {
// Get a new client
client, err := api.NewClient(api.DefaultConfig())
if err != nil {
panic(err)
}
// Get a handle to the KV API
kv := client.KV()
// PUT a new KV pair
p := &api.KVPair{Key: "REDIS_MAXCLIENTS", Value: []byte("1000")}
_, err = kv.Put(p, nil)
if err != nil {
panic(err)
}
// Lookup the pair
pair, _, err := kv.Get("REDIS_MAXCLIENTS", nil)
if err != nil {
panic(err)
}
fmt.Printf("KV: %v %s\n", pair.Key, pair.Value)
}
输出:
dotzdeMacBook-Pro-2:src dotz$ go run consul_eg.go
KV: REDIS_MAXCLIENTS 1000