etcd

package
v3.1.32 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

* KV 存储相关方法 提供对etcd KV存储的封装,包括Put、Get等操作

app.EnableEtcdDiscovery(nil) discovery := app.EtcdDiscovery

// 追加白名单(多个服务可写同一个 key,不会覆盖已有路径)

discovery.Add("gateway/public_routes", []string{
 "/v1/auth/user/login",
 "/v1/auth/user/register",
 "/v1/oauth",
})

// 读白名单 var routes []string

if err := discovery.Get("gateway/public_routes", &routes); err != nil {
 // key 不存在时用本地默认值
 routes = []string{"/v1/auth/user/login", "/v1/auth/user/register"}
}

// watch 白名单变化(多网关实时同步)

cancel, _ := discovery.WatchKV("gateway/public_routes", func(key, value string) {
 var newRoutes []string
 json.Unmarshal([]byte(value), &newRoutes)
 // 更新内存中的白名单
 updatePublicRoutes(newRoutes)
})

defer cancel()

Index

Constants

View Source
const KVPrefix = "/config/"

KVPrefix 配置中心旧版默认前缀。

View Source
const Scheme = "etcd"

Variables

View Source
var (
	// ErrInvalidLeaseTTL 表示租约秒数不能交给 etcd 创建有效租约。
	ErrInvalidLeaseTTL = errors.New("etcd lease ttl must be positive")
	// ErrInvalidLeaseID 表示调用方没有提供由 GrantLease 返回的有效租约 ID。
	ErrInvalidLeaseID = errors.New("etcd lease id must be positive")
	// ErrInvalidLeaseKey 表示 key 不是当前 Discovery namespace 下的相对逻辑 key。
	ErrInvalidLeaseKey = errors.New("etcd lease key must be a non-empty relative key")
)

Functions

func Dial

func Dial(serviceName string, opts ...grpc.DialOption) (*grpc.ClientConn, error)

Dial 创建基于 etcd 服务发现的 gRPC 客户端连接

func InitEtcdResolver

func InitEtcdResolver(discovery *Discovery)

func NamespacePrefix added in v3.1.26

func NamespacePrefix(namespace, logicalPrefix string) string

NamespacePrefix 将逻辑前缀放入规范化后的项目命名空间。

Types

type Discovery

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

func NewDiscovery

func NewDiscovery(opts *Options) (*Discovery, error)

func (*Discovery) Add added in v3.1.18

func (d *Discovery) Add(key string, value []string, opts ...clientv3.OpOption) error

Add appends string values to a JSON []string stored at key. It preserves existing order, skips duplicates, and uses an etcd transaction so concurrent Add calls do not overwrite each other's additions.

func (*Discovery) Close

func (d *Discovery) Close() error

func (*Discovery) CompareAndPut added in v3.1.28

func (d *Discovery) CompareAndPut(ctx context.Context, key string, expectedModRevision int64, value string, leaseID LeaseID) (bool, error)

CompareAndPut 以 revision CAS 原子写入 value 并绑定租约。 expectedModRevision=0 只允许 key 尚未创建;CAS 冲突返回 false, nil。

func (*Discovery) Delete added in v3.1.16

func (d *Discovery) Delete(key string) error

Delete 删除键

func (*Discovery) Get added in v3.1.16

func (d *Discovery) Get(key string, out any) error

Get 获取值并 JSON 反序列化

func (*Discovery) GetPrefix added in v3.1.16

func (d *Discovery) GetPrefix(prefix string) (map[string]string, error)

GetPrefix 按前缀获取所有键值对,返回原始 map[string]string

func (*Discovery) GetRevision added in v3.1.28

func (d *Discovery) GetRevision(ctx context.Context, key string) (revision KVRevision, found bool, err error)

GetRevision 读取相对逻辑 key 的当前值及 CAS revision。 found=false 表示 key 不存在,此时创建方应使用 expectedModRevision=0。

func (*Discovery) GetServices

func (d *Discovery) GetServices(serviceName string) []*ServiceInfo

func (*Discovery) GetString added in v3.1.16

func (d *Discovery) GetString(key string) (string, error)

GetString 获取字符串值

func (*Discovery) GrantLease added in v3.1.28

func (d *Discovery) GrantLease(ctx context.Context, ttlSeconds int64) (LeaseID, error)

GrantLease 创建以秒为单位的 etcd 租约。

func (*Discovery) KeepAliveLease added in v3.1.28

func (d *Discovery) KeepAliveLease(ctx context.Context, id LeaseID) (<-chan LeaseKeepAlive, error)

KeepAliveLease 持续续租,直到 context 取消、租约丢失或 Discovery 关闭。 返回 channel 会在上述任一终止条件发生时关闭。

func (*Discovery) Namespace added in v3.1.26

func (d *Discovery) Namespace() string

Namespace 返回当前 Discovery 使用的规范化命名空间。

func (*Discovery) Put added in v3.1.16

func (d *Discovery) Put(key string, value any, opts ...clientv3.OpOption) error

Put 存储键值对,value 会被 JSON 序列化

func (*Discovery) PutString added in v3.1.16

func (d *Discovery) PutString(key string, value string, opts ...clientv3.OpOption) error

PutString 存储字符串值,跳过 JSON 序列化

func (*Discovery) RevokeLease added in v3.1.28

func (d *Discovery) RevokeLease(ctx context.Context, id LeaseID) error

RevokeLease 主动撤销租约及其绑定的所有 key。

func (*Discovery) Subscribe

func (d *Discovery) Subscribe(serviceName string, fn func()) func()

func (*Discovery) Watch

func (d *Discovery) Watch(serviceName string) error

func (*Discovery) WatchKV added in v3.1.16

func (d *Discovery) WatchKV(key string, onChange func(key, value string)) (cancel func(), err error)

WatchKV 监听 key 变化,返回取消函数 onChange 接收 key 和新值,删除时 value 为空

func (*Discovery) WatchPrefix added in v3.1.16

func (d *Discovery) WatchPrefix(prefix string, onChange func(key, value string)) (cancel func(), err error)

WatchPrefix 监听前缀下所有 key 变化

type EtcdResolverBuilder

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

func (*EtcdResolverBuilder) Build

func (*EtcdResolverBuilder) Scheme

func (b *EtcdResolverBuilder) Scheme() string

type KVRevision added in v3.1.28

type KVRevision struct {
	Value       string
	ModRevision int64
}

KVRevision 返回 CAS 所需的当前值和 ModRevision。

type LeaseID added in v3.1.28

type LeaseID int64

LeaseID 是由当前 Discovery 所拥有 etcd client 签发的租约标识。

type LeaseKeepAlive added in v3.1.28

type LeaseKeepAlive struct {
	ID  LeaseID
	TTL int64
}

LeaseKeepAlive 是 keepalive 流中与调用方相关的最小租约状态。

type Options

type Options struct {
	// Namespace 隔离共享 etcd 中不同项目的数据;为空时保持旧 key 布局
	Namespace string

	// etcd 客户端配置
	Endpoints   []string
	Username    string
	Password    string
	DialTimeout time.Duration

	// 服务注册配置
	ServiceName string
	ServiceAddr string
	ServiceID   string
	TTL         int64 // 租约时间(秒)
	Version     string

	// 元数据
	Metadata map[string]string
}

func DefaultOptions

func DefaultOptions() *Options

func (*Options) ConfigPrefix added in v3.1.26

func (o *Options) ConfigPrefix() string

ConfigPrefix 返回当前命名空间下的配置根前缀。

func (*Options) ServiceKey

func (o *Options) ServiceKey() string

生成 etcd key

func (*Options) ServicePrefix

func (o *Options) ServicePrefix() string

服务前缀(用于发现)

func (*Options) ServiceRoot added in v3.1.26

func (o *Options) ServiceRoot() string

ServiceRoot 返回当前命名空间下的服务根前缀。

type Registry

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

func NewRegistry

func NewRegistry(opts *Options) (*Registry, error)

func (*Registry) Deregister

func (r *Registry) Deregister() error

Deregister 注销服务

func (*Registry) Register

func (r *Registry) Register() error

type ServiceInfo

type ServiceInfo struct {
	Name     string            `json:"name"`
	Addr     string            `json:"addr"`
	ID       string            `json:"id"`
	Version  string            `json:"version"`
	Metadata map[string]string `json:"metadata"`
	TTL      int64             `json:"ttl"`
}

ServiceInfo 服务信息

Jump to

Keyboard shortcuts

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