betcd

package module
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2022 License: MIT Imports: 9 Imported by: 0

README

betcd

配置中心

代码

package main

import (
	"encoding/xml"
	"time"

	"github.com/grpc-boot/base"
	"github.com/grpc-boot/betcd"
	clientv3 "go.etcd.io/etcd/client/v3"
)

var (
	etcdClient *clientv3.Client
	config     betcd.Config
)

const (
	ConfVersion = `browser/conf/app/version`
	ConfLimit   = `browser/conf/app/limit`
	ConfRedis   = `browser/conf/app/redis`
	ConfMysql   = `browser/conf/app/mysql`
)

var (
	keyOptions = []betcd.KeyOption{
		{Key: ConfVersion, Type: betcd.String},
		{Key: ConfLimit, Type: betcd.Json},
		{Key: ConfRedis, Type: betcd.Yaml},
		{Key: ConfMysql, Deserialize: func(data []byte) (value interface{}, err error) {
			var val MysqlOption
			err = xml.Unmarshal(data, &val)
			return val, err
		}},
	}
)

type MysqlOption struct {
	Host     string `xml:"host"`
	Port     uint16 `xml:"port"`
	DbName   string `xml:"dbname"`
	UserName string `xml:"userName"`
	Password string `xml:"password"`
}

func init() {
	var err error

	etcdClient, err = clientv3.New(clientv3.Config{
		Endpoints:            []string{"127.0.0.1:2379"},
		DialTimeout:          time.Second,
		DialKeepAliveTime:    time.Second * 100,
		DialKeepAliveTimeout: time.Second * 10,
	})

	if err != nil {
		base.RedFatal("init etcd err:%s", err.Error())
	}

	config, err = betcd.NewConfigWithClient(etcdClient, []string{"browser/conf/app"}, keyOptions, clientv3.WithPrefix())
	if err != nil {
		base.RedFatal("init etcd config err:%s", err.Error())
	}
}

func main() {
	go logging()

	_, err := config.Put(ConfVersion, "12.0.0.3", time.Second)
	if err != nil {
		base.Red("put %s err:%s", ConfVersion, err.Error())
	}

	limitConf := map[string]interface{}{
		"/user/info": map[string]interface{}{
			"limit": 5000,
		},
		"/user/login": map[string]interface{}{
			"limit": 500,
		},
	}

	data, _ := base.JsonEncode(limitConf)
	_, err = config.Put(ConfLimit, base.Bytes2String(data), time.Second)
	if err != nil {
		base.Red("put %s err:%s", ConfLimit, err.Error())
	}

	redisConf := map[string]interface{}{
		"host": "127.0.0.1",
		"port": 6378,
		"auth": "ab2343sadfa23",
	}
	data, _ = base.YamlEncode(redisConf)
	_, err = config.Put(ConfRedis, base.Bytes2String(data), time.Second)
	if err != nil {
		base.Red("put %s err:%s", ConfRedis, err.Error())
	}

	mysqlConf := MysqlOption{
		Host:     "127.0.0.1",
		Port:     3309,
		DbName:   "test",
		UserName: "test",
		Password: "12345678",
	}
	data, _ = xml.Marshal(mysqlConf)
	_, err = config.Put(ConfMysql, base.Bytes2String(data), time.Second)
	if err != nil {
		base.Red("put %s err:%s", ConfMysql, err.Error())
	}

	defer config.Close()

	var done chan struct{}
	<-done
}

func logging() {
	tick := time.NewTicker(time.Second)
	for range tick.C {
		val, exists := config.Get(ConfVersion)
		base.Green("%s--%+v--%t", ConfVersion, val, exists)

		val, exists = config.Get(ConfLimit)
		base.Green("%s--%+v--%t", ConfLimit, val, exists)

		val, exists = config.Get(ConfRedis)
		base.Green("%s--%+v--%t", ConfRedis, val, exists)

		val, exists = config.Get(ConfMysql)
		base.Green("%s--%+v--%t", ConfMysql, val, exists)
	}
}

服务注册与发现
package main

import (
	"context"
	"time"

	"github.com/grpc-boot/base"
	"github.com/grpc-boot/betcd"
	clientv3 "go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/client/v3/naming/endpoints"
)

var (
	etcdClient *clientv3.Client
	naming     betcd.Naming
)

const (
	ServiceApp = `browser/services/app`
)

func init() {
	var err error

	etcdClient, err = clientv3.New(clientv3.Config{
		Endpoints:            []string{"127.0.0.1:2379"},
		DialTimeout:          time.Second,
		DialKeepAliveTime:    time.Second * 100,
		DialKeepAliveTimeout: time.Second * 10,
	})

	if err != nil {
		base.RedFatal("init etcd err:%s", err.Error())
	}

	naming, err = betcd.NewNamingWithClient(etcdClient, ServiceApp)
	if err != nil {
		base.RedFatal("init etcd naming err:%s", err.Error())
	}
}

func main() {
	go logging()

	_, err := naming.Register(30, endpoints.Endpoint{
		Addr: "127.0.0.1:8082",
		Metadata: map[string]interface{}{
			"version": "1.0.0",
			"weight":  10,
			"auth":    true,
		},
	})

	if err != nil {
		base.RedFatal("register err:%s", err.Error())
	}

	_, err = naming.Register(30, endpoints.Endpoint{
		Addr: "127.0.0.1:8083",
		Metadata: map[string]interface{}{
			"version": "1.0.0",
			"weight":  100,
			"auth":    true,
		},
	})
	if err != nil {
		base.RedFatal("register err:%s", err.Error())
	}

	var done chan struct{}
	<-done
}

func logging() {
	tick := time.NewTicker(time.Second)

	for range tick.C {
		endpointMap, err := naming.List(context.TODO())
		if err != nil {
			base.Red("list endpoint err:%s", err.Error())
			continue
		}

		base.Green("%+v", endpointMap)
	}
}

Documentation

Index

Constants

View Source
const (
	String = "string"
	Json   = "json"
	Yaml   = "yaml"
)

Variables

This section is empty.

Functions

func JsonMapDeserialize

func JsonMapDeserialize(data []byte) (value interface{}, err error)

JsonMapDeserialize Json反序列化为map[string]interface{}

func StringDeserialize

func StringDeserialize(data []byte) (value interface{}, err error)

StringDeserialize 字符串

func YamlMapDeserialize

func YamlMapDeserialize(data []byte) (value interface{}, err error)

YamlMapDeserialize Yaml反序列化为map[string]interface{}

Types

type Config

type Config interface {
	// LoadKey 加载前缀到缓存
	LoadKey(prefix string, opts ...clientv3.OpOption) (err error)
	// Watch 监视某个Key,返回WatchChan
	Watch(ctx context.Context, key string, opts ...clientv3.OpOption) (wch clientv3.WatchChan)
	// WatchKey4Cache 监视某个Key,并修改cache
	WatchKey4Cache(key string, opts ...clientv3.OpOption)
	// Put 修改某个Key值
	Put(key string, value string, timeout time.Duration, opts ...clientv3.OpOption) (resp *clientv3.PutResponse, err error)
	// PutContext with context修改某个Key值
	PutContext(ctx context.Context, key string, value string, opts ...clientv3.OpOption) (resp *clientv3.PutResponse, err error)
	// Get 获取数据
	Get(key string) (value interface{}, exists bool)
	// GetRemote 从etcd远程获取数据
	GetRemote(key string, timeout time.Duration) (kvs []*mvccpb.KeyValue, err error)
	// GetRemoteContext with context从etcd远程获取数据
	GetRemoteContext(ctx context.Context, key string) (kvs []*mvccpb.KeyValue, err error)
	// Delete 删除某个Key数据
	Delete(key string, timeout time.Duration, opts ...clientv3.OpOption) (resp *clientv3.DeleteResponse, err error)
	// Connection 获取ectd config
	Connection() (client *clientv3.Client)
	// Close ---
	Close() (err error)
}

Config etcd Config

func NewConfig

func NewConfig(v3Conf *clientv3.Config, confOption ConfigOption, watchOptions ...clientv3.OpOption) (c Config, changeChan <-chan shardmap.ChangeEvent, err error)

func NewConfigWithClient

func NewConfigWithClient(client *clientv3.Client, co ConfigOption, watchOptions ...clientv3.OpOption) (c Config, changeChan <-chan shardmap.ChangeEvent, err error)

type ConfigOption

type ConfigOption struct {
	PrefixList    []string    `json:"prefixList" yaml:"prefixList"`
	KeyOptionList []KeyOption `json:"keyOptionList" yaml:"keyOptionList"`
	ChannelSize   uint16      `json:"channelSize" yaml:"channelSize"`
}

ConfigOption 配置选项

type Deserialize

type Deserialize func(data []byte) (value interface{}, err error)

Deserialize 反序列化函数

type Deserializer

type Deserializer interface {
	// Deserialize 反序列化
	Deserialize(key string, val []byte) (value interface{}, err error)
}

Deserializer 反序列化工具

func NewDeserializer

func NewDeserializer(options map[string]KeyOption) Deserializer

NewDeserializer 实例化反序列化工具对象

type KeyOption

type KeyOption struct {
	Key         string `json:"key" yaml:"key"`
	Type        string `json:"type" yaml:"type"`
	Deserialize Deserialize
}

KeyOption Key配置

type Naming

type Naming interface {
	// List 列表
	List(ctx context.Context) (endpoints endpoints.Key2EndpointMap, err error)
	// Add 添加
	Add(endpoint endpoints.Endpoint, opts ...clientv3.OpOption) (err error)
	// AddContext with context添加
	AddContext(ctx context.Context, endpoint endpoints.Endpoint, opts ...clientv3.OpOption) (err error)
	// Register 注册
	Register(keepAliveSecond int64, endpoint endpoints.Endpoint, opts ...clientv3.OpOption) (ch <-chan *clientv3.LeaseKeepAliveResponse, err error)
	// Del 删除
	Del(endpoint endpoints.Endpoint, opts ...clientv3.OpOption) (err error)
	// DelContext with context删除
	DelContext(ctx context.Context, endpoint endpoints.Endpoint, opts ...clientv3.OpOption) (err error)
	// ChangeEndpoint 更换
	ChangeEndpoint(ctx context.Context, new endpoints.Endpoint) (err error)
	// DialGrpc ---
	DialGrpc(opts ...grpc.DialOption) (*grpc.ClientConn, error)
}

func NewNaming

func NewNaming(v3Conf *clientv3.Config, service string) (n Naming, err error)

func NewNamingWithClient

func NewNamingWithClient(client *clientv3.Client, service string) (n Naming, err error)

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL