Centos7 系统:
#yum install etcd
Centos8 系统:
暂不支持yum安装etcd,可以git clone 安装
C/S 框架
启动配置文件:
/etc/etcd/etcd.conf
启动命令:
etcd -data-dir ~/vpp.etcd -advertise-client-urls http://0.0.0.0:2379 -listen-client-urls http://0.0.0.0:2379
数据存储在 vpp.etcd
启动服务后,搞个客户端程序就可以正常使用了
Etcd 客户端程序
package etcdclient
import (
"go.etcd.io/etcd/clientv3"
)
var (
//Deal with the timeout
dialTimeout = 5 * time.Second
//RequestTimeout The request timeout
RequestTimeout = 10 * time.Second
)
var etcdCliV3 *clientv3.Client
//New ETCD client
func GetEtcdClientV3() (cli *clientv3.Client, err error) {
if etcdCliV3 != nil {
cli = etcdCliV3
err = nil
} else {
cli = nil
err = fmt.Errorf("etcdCliV3 not initialized")
}
return
}
//Create a new ETCD client connection
func NewEtcdClientV3(endpoint []string) (cli *clientv3.Client, err error) {
fmt.Printf("the etcd link -%s\n", endpoint)
cli, err = clientv3.New(clientv3.Config{
Endpoints: endpoint,
DialTimeout: dialTimeout,
})
if err != nil {
// handle error!
log.Error("agent connect etcd failed: %v", err)
os.Exit(1)
}
etcdCliV3 = cli
log.Info("connect etcd successfully")
return
}
//close etcd client
func CloseEtcdClientV3() {
etcdCliV3.Close()
log.Info("close etcd client connection")
}
//Sets the keys and values for the ETCD
func EtcdClientV3Put(key string, val string) (err1 error) {
//...
return
}
//Delete the value of the key
func EtcdClientV3Del(key string) (err1 error) {
//...
}
//Gets the value of the key
func EtcdClientV3Get(key string) (result string, err1 error) {
//...
}
//EtcdClientV3GetPrefix Get the data from the ETCD database
func EtcdClientV3GetPrefix(key string, onGet func([]byte, []byte)) (err1 error) {
//...
}
//EtcdClientV3DeleteAll Empty the ETCD database
func EtcdClientV3DeleteAll() (err error) {
if etcdCliV3 == nil {
return fmt.Errorf("cli not initialize")
}
ctx, cancel := context.WithTimeout(context.Background(), RequestTimeout)
_, err = etcdCliV3.Delete(ctx, "", clientv3.WithPrefix())
cancel()
if err != nil {
switch err {
case context.Canceled:
log.Info("ctx is canceled by another routine: %v", err)
case context.DeadlineExceeded:
log.Info("ctx is attached with a deadline is exceeded: %v", err)
default:
log.Info("bad cluster endpoints, which are not etcd servers: %v", err)
}
return err
}
return nil
}
func main(){
//...
etcdclient.NewEtcdClientV3("[127.0.0.1:2379]")
//...请开始你的业务表演
<-c
etcdclient.CloseEtcdClientV3()
}