eetcd

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2022 License: MIT Imports: 16 Imported by: 0

README

eetcd 组件使用指南

goproxy.cn Release Example Doc

1 简介

etcd 进行了轻量封装,并提供了以下功能:

  • 规范了标准配置格式,提供了统一的 Load().Build() 方法。
  • 支持grpc的服务注册与发现
  • 支持etcd的配置中心

2 使用方式

go get github.com/ego-component/eetcd

4 配置

type config struct {
    Addrs                        []string      // 地址
    CertFile                     string        // cert file
    KeyFile                      string        // key file
    CaCert                       string        // ca cert
    UserName                     string        // 用户名
    Password                     string        // 密码
    ConnectTimeout               time.Duration // 连接超时时间
    AutoSyncInterval             time.Duration // 自动同步member list的间隔
    EnableBasicAuth              bool          // 是否开启认证
    EnableSecure                 bool          // 是否开启安全
    EnableBlock                  bool          // 是否开启阻塞,默认开启
    EnableFailOnNonTempDialError bool          // 是否开启gRPC连接的错误信息
}

5 服务注册

5.1 用户配置

[etcd]
addrs=["127.0.0.1:2379"]
connectTimeout = "1s"
secure = false
[registry]
scheme = "etcd" # grpc resolver默认scheme为"etcd",你可以自行修改
#ServiceTTL = "10s"

5.2 用户代码

配置创建一个 etcd 的配置项,其中内容按照上文配置进行填写。以上这个示例里这个配置key是etcd

代码中创建一个 etcd 实例 eetcd.Load({key}).Build(),代码中的 key 和配置中的 key 要保持一致。

package main

import (
	"context"

	"github.com/ego-component/eetcd"
	"github.com/ego-component/eetcd/examples/helloworld"
	"github.com/ego-component/eetcd/registry"
	"github.com/gotomicro/ego"
	"github.com/gotomicro/ego/core/elog"
	"github.com/gotomicro/ego/server"
	"github.com/gotomicro/ego/server/egrpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

//  export EGO_DEBUG=true && go run main.go --config=config.toml
func main() {
	if err := ego.New().
		Registry(registry.Load("registry").Build(registry.WithClientEtcd(eetcd.Load("etcd").Build()))).
		Serve(func() server.Server {
			component := egrpc.Load("server.grpc").Build()
			helloworld.RegisterGreeterServer(component.Server, &Greeter{})
			return component
		}()).Run(); err != nil {
		elog.Panic("startup", elog.Any("err", err))
	}
}

type Greeter struct {
	helloworld.UnimplementedGreeterServer
}

func (g Greeter) SayHello(context context.Context, request *helloworld.HelloRequest) (*helloworld.HelloResponse, error) {
	if request.Name == "error" {
		return nil, status.Error(codes.Unavailable, "error")
	}

	return &helloworld.HelloResponse{
		Message: "Hello EGO",
	}, nil
}

5.3 数据展示

img img

6 服务发现

6.1 用户配置


[etcd]
addrs=["127.0.0.1:2379"]
connectTimeout = "1s"
secure = false
[registry]
scheme = "etcd" # grpc resolver默认scheme为"etcd",你可以自行修改

6.2 用户代码

配置创建一个 etcd 的配置项,其中内容按照上文配置进行填写。以上这个示例里这个配置key是etcd

代码中创建一个 etcd 实例 eetcd.Load({key}).Build(),代码中的 key 和配置中的 key 要保持一致。

package main

import (
	"context"

	"github.com/gotomicro/ego"
	"github.com/gotomicro/ego/client/egrpc"
	"github.com/gotomicro/ego/core/elog"

	"github.com/ego-component/eetcd"
	"github.com/ego-component/eetcd/examples/helloworld"
	"github.com/ego-component/eetcd/registry"
)

func main() {
	if err := ego.New().Invoker(
		invokerGrpc,
		callGrpc,
	).Run(); err != nil {
		elog.Error("startup", elog.FieldErr(err))
	}
}

var grpcComp helloworld.GreeterClient

func invokerGrpc() error {
	// 注册resolver
	registry.Load("registry").Build(registry.WithClientEtcd(eetcd.Load("etcd").Build()))
	grpcConn := egrpc.Load("grpc.test").Build()
	grpcComp = helloworld.NewGreeterClient(grpcConn.ClientConn)
	return nil
}

func callGrpc() error {
	_, err := grpcComp.SayHello(context.Background(), &helloworld.HelloRequest{
		Name: "i am client",
	})
	if err != nil {
		return err
	}

	_, err = grpcComp.SayHello(context.Background(), &helloworld.HelloRequest{
		Name: "error",
	})
	if err != nil {
		return err
	}
	return nil
}

6.3 数据展示

img

查看全部租期

etcdctl lease list found 1 leases 694d79ada4e6c82c

查看某个租期信息

etcdctl lease timetolive 694d79ada4e6c82c --keys lease 694d79ada4e6c82c granted with TTL(10s), remaining(9s), attached keys([/ego/main/providers/grpc://0.0.0.0:9003])


Documentation

Index

Constants

View Source
const PackageName = "component.eetcd"

Variables

This section is empty.

Functions

func DefaultConfig

func DefaultConfig() *config

DefaultConfig 返回默认配置

Types

type Component

type Component struct {
	*clientv3.Client
	// contains filtered or unexported fields
}

Component ...

func (*Component) DelPrefix

func (c *Component) DelPrefix(ctx context.Context, prefix string) (deleted int64, err error)

DelPrefix 按前缀删除

func (*Component) GetKeyValue

func (c *Component) GetKeyValue(ctx context.Context, key string) (kv *mvccpb.KeyValue, err error)

GetKeyValue queries etcd key, returns mvccpb.KeyValue

func (*Component) GetLeaseSession

func (c *Component) GetLeaseSession(ctx context.Context, opts ...concurrency.SessionOption) (leaseSession *concurrency.Session, err error)

GetLeaseSession 创建租约会话

func (*Component) GetPrefix

func (c *Component) GetPrefix(ctx context.Context, prefix string) (map[string]string, error)

GetPrefix get prefix

func (*Component) GetValues

func (c *Component) GetValues(ctx context.Context, keys ...string) (map[string]string, error)

GetValues queries etcd for keys prefixed by prefix.

func (*Component) NewMutex

func (c *Component) NewMutex(key string, opts ...concurrency.SessionOption) (mutex *Mutex, err error)

NewMutex ...

func (*Component) WatchPrefix

func (c *Component) WatchPrefix(ctx context.Context, prefix string) (*Watch, error)

WatchPrefix 监听某个key

type Container

type Container struct {
	// contains filtered or unexported fields
}

func DefaultContainer

func DefaultContainer() *Container

func Load

func Load(key string) *Container

func (*Container) Build

func (c *Container) Build(options ...Option) *Component

Build 构建组件

type Mutex

type Mutex struct {
	// contains filtered or unexported fields
}

Mutex ...

func (*Mutex) Lock

func (mutex *Mutex) Lock(ctx context.Context) (err error)

Lock ...

func (*Mutex) Unlock

func (mutex *Mutex) Unlock(ctx context.Context) (err error)

Unlock ...

type Option

type Option func(c *Container)

func WithAddrs

func WithAddrs(addrs []string) Option

func WithCaCert

func WithCaCert(caCert string) Option

func WithCertFile

func WithCertFile(certFile string) Option

func WithEnableBasicAuth

func WithEnableBasicAuth(enable bool) Option

func WithEnableSecure

func WithEnableSecure(secure bool) Option

func WithKeyFile

func WithKeyFile(keyFile string) Option

func WithPassword

func WithPassword(password string) Option

func WithUserName

func WithUserName(userName string) Option

type Watch

type Watch struct {
	// contains filtered or unexported fields
}

Watch A watch only tells the latest revision

func (*Watch) C

func (w *Watch) C() chan *clientv3.Event

C ...

func (*Watch) Close

func (w *Watch) Close() error

Close watch

func (*Watch) IncipientKeyValues

func (w *Watch) IncipientKeyValues() []*mvccpb.KeyValue

IncipientKeyValues incipient key and values

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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