etcd

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 11 Imported by: 0

README

go-boot-etcd

Go Version License Build Status Go Reference Go Report Card

基于 go-boot 的 etcd 注册中心与配置中心集成模块。将 etcd 无缝集成到 go-boot 的 IoC 容器和自动配置体系中,提供服务注册、服务发现、配置加载和配置监听能力。

设计理念:遵循 go-boot 的开发规范,将 etcd 作为 center.Registryconfig.ConfigCenter 接口的实现,通过自动配置实现零代码启动服务注册与配置管理。

整体架构

┌───────────────────────────────────────────────────────────────────────┐
│                    go-boot ApplicationContext                         │
│  ┌───────────┐ ┌──────────────┐ ┌───────────┐ ┌───────────┐           │
│  │ Container │ │  Environment │ │ Lifecycle │ │ EventBus  │           │
│  └───────────┘ └──────────────┘ └───────────┘ └───────────┘           │
│                       ┌─────────────────────┐                         │
│                       │ AutoConfig Registry │                         │
│                       └─────────────────────┘                         │
└───────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
                    ┌───────────────────────────────┐
                    │    go-boot-etcd Starter       │
                    │  ┌─────────────────────────┐  │
                    │  │ EtcdRegistry Bean       │  │
                    │  │ (center.Registry)       │  │
                    │  │ EtcdConfigCenter Bean   │  │
                    │  │ (config.ConfigCenter)   │  │
                    │  │ Lease & KeepAlive       │  │
                    │  └─────────────────────────┘  │
                    └───────────────────────────────┘

目录

快速开始

安装
# 安装核心框架
go get github.com/xudefa/go-boot

# 安装 etcd 集成模块
go get github.com/xudefa/go-boot-etcd
最小示例
package main

import (
    "github.com/xudefa/go-boot/boot"
    "github.com/xudefa/go-boot/center"
)

func main() {
    app, err := boot.NewApplication(
        boot.WithAppName("my-service"),
        boot.WithVersion("1.0.0"),
        boot.WithProperty("etcd.enabled", "true"),
        boot.WithProperty("etcd.endpoints", "127.0.0.1:2379"),
    )
    if err != nil {
        panic(err)
    }
    defer app.Stop()

    // 获取注册中心(自动注入)
    registry := app.Container().Get("etcdRegistry").(center.Registry)

    // 注册服务
    registry.Register(context.Background(), center.InstanceInfo{
        ServiceName: "my-service",
        Host:        "127.0.0.1",
        Port:        8080,
    })

    // 发现服务
    instances, _ := registry.Discover(context.Background(), "my-service")
    for _, inst := range instances {
        fmt.Printf("发现实例: %s:%d\n", inst.Host, inst.Port)
    }

    app.Start()
    app.WaitForSignal()
}

功能特性

特性 说明
注册中心 实现 go-boot center.Registry 接口
配置中心 实现 go-boot config.ConfigCenter 接口
自动配置 通过 etcd.enabled=true 自动启用
租约机制 使用 etcd Lease + KeepAlive 实现健康检测
服务发现 支持前缀查询和 Watch 监听实例变化
配置监听 支持配置变更的实时监听
函数式选项 灵活的连接配置(Endpoints、Prefix、TTL 等)

服务注册与发现

创建注册中心
registry, err := etcd.NewEtcdRegistry(
    etcd.WithEndpoints("127.0.0.1:2379"),
    etcd.WithPrefix("/services"),
    etcd.WithTTL(30*time.Second),
)
注册服务
registry.Register(ctx, center.InstanceInfo{
    ServiceName: "user-service",
    ID:          "instance-001",
    Host:        "127.0.0.1",
    Port:        8080,
    Weight:      10,
    Healthy:     true,
    Metadata:    map[string]string{"version": "1.0.0"},
})
发现服务
instances, err := registry.Discover(ctx, "user-service")
监听服务变化
ch, err := registry.Watch(ctx, "user-service")
for instances := range ch {
    fmt.Printf("当前在线实例: %d\n", len(instances))
}

配置中心

启用配置中心
# application.yml
etcd:
  enabled: true
  endpoints: "127.0.0.1:2379"
  config-center:
    enabled: true
    data-id: "app-config"
    group: "DEFAULT_GROUP"
    prefix: "/config"
加载配置
configCenter := app.Container().Get("configCenter").(config.ConfigCenter)
data, err := configCenter.Load()
监听配置变更
configCenter.Watch("app-config", func(data config.ConfigData) {
    fmt.Printf("配置已更新: %v\n", data)
})

配置选项

通过 boot.WithProperty() 或配置文件设置:

配置项 默认值 说明
etcd.enabled false 是否启用 etcd 注册中心
etcd.endpoints localhost:2379 etcd 服务端点(逗号分隔)
etcd.prefix /services 服务注册前缀
etcd.ttl 30s 租约 TTL
etcd.dial-timeout 5s 连接超时
etcd.config-center.enabled false 是否启用配置中心
etcd.config-center.data-id app-config 配置 DataID
etcd.config-center.group DEFAULT_GROUP 配置分组
etcd.config-center.prefix /config 配置前缀
示例配置
# application.yml
etcd:
  enabled: true
  endpoints: "127.0.0.1:2379,127.0.0.1:2380"
  prefix: "/services"
  ttl: "30s"
  dial-timeout: "5s"
  config-center:
    enabled: true
    data-id: "my-app"
    prefix: "/config/my-app"

项目结构

go-boot-etcd/
├── etcd.go              # EtcdRegistry 实现 center.Registry
├── etcd_config.go       # 配置选项(Config, Option)
├── config_center.go     # EtcdConfigCenter 实现 config.ConfigCenter
├── autoconfig.go        # 自动配置注册
├── etcd_test.go         # 单元测试
├── README.md
├── LICENSE
└── go.mod

开发指南

构建
go build ./...
测试
go test ./...
go test -cover ./...       # 带覆盖率
go test -race ./...        # 数据竞争检测
代码规范
go fmt ./...
golangci-lint run

贡献

欢迎提交 Issue 和 Pull Request!详细贡献指南请参阅 CONTRIBUTING.md

许可证

本项目采用 MIT 许可证 — 详情请参阅 LICENSE 文件。

Documentation

Overview

Package etcd 提供 etcd 配置中心实现

Package etcd 基于 etcd 提供注册中心实现。

该包将 etcd 与 go-boot 服务发现和注册中心接口集成, 使用 etcd Lease 机制实现健康检测,支持服务注册、发现和 Watch。

定义:

  • EtcdRegistry: 注册中心实现了 center.Registry 接口
  • Config: etcd 配置
  • Option: 配置选项函数

快速开始:

// 创建 etcd 注册中心
registry, err := etcd.NewEtcdRegistry(
    etcd.WithEndpoints("127.0.0.1:2379"),
)

// 注册服务
registry.Register(ctx, center.InstanceInfo{
    ServiceName: "my-service",
    Host:        "127.0.0.1",
    Port:        8080,
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	Endpoints   []string
	Prefix      string
	TTL         time.Duration
	DialTimeout time.Duration
	TLS         *tls.Config
	Container   core.Container
}

Config etcd 注册中心配置。

type EtcdConfigCenter

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

func NewEtcdConfigCenter

func NewEtcdConfigCenter(cfg *config.ConfigCenterConfig) (*EtcdConfigCenter, error)

func (*EtcdConfigCenter) Close

func (e *EtcdConfigCenter) Close() error

Close 关闭客户端

func (*EtcdConfigCenter) Load

func (e *EtcdConfigCenter) Load() (config.ConfigData, error)

Load 加载所有配置数据

func (*EtcdConfigCenter) Watch

func (e *EtcdConfigCenter) Watch(key string, callback func(config.ConfigData)) error

Watch 监控配置变更

type EtcdRegistry

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

EtcdRegistry 基于 etcd 实现的注册中心。 服务实例信息存储为 JSON 格式的 value,key 为 {prefix}/{serviceName}/{instanceID}。 使用 etcd Lease 机制实现健康检测:注册时创建租约并通过 KeepAlive 续约。

func NewEtcdRegistry

func NewEtcdRegistry(opts ...Option) (*EtcdRegistry, error)

NewEtcdRegistry 创建 etcd 注册中心实例。 支持通过 Option 函数式选项配置 endpoints、前缀、TTL 等参数。

func (*EtcdRegistry) Deregister

func (r *EtcdRegistry) Deregister(ctx context.Context, info center.InstanceInfo) error

Deregister 从 etcd 中删除指定服务实例。 实例被删除后,租约将不再被续约,等待 TTL 过期后自动清理。

func (*EtcdRegistry) Discover

func (r *EtcdRegistry) Discover(ctx context.Context, serviceName string) ([]center.InstanceInfo, error)

Discover 发现指定服务的所有在线实例。 通过前缀查询 {prefix}/{serviceName} 下的所有 key,反序列化得到实例列表。

func (*EtcdRegistry) Register

func (r *EtcdRegistry) Register(ctx context.Context, info center.InstanceInfo) error

Register 向 etcd 注册一个服务实例。 步骤:

  1. 将实例信息序列化为 JSON
  2. 创建租约(TTL 由配置决定)
  3. 将实例数据写入 etcd,绑定租约
  4. 启动后台 KeepAlive 保持租约有效

KeepAlive 使用的 context 从调用方 context 分离,不受其取消/超时影响, 调用方应通过 Deregister 来注销实例。

func (*EtcdRegistry) Watch

func (r *EtcdRegistry) Watch(ctx context.Context, serviceName string) (<-chan []center.InstanceInfo, error)

Watch 监听指定服务的实例变化。 底层使用 etcd Watch 监听 {prefix}/{serviceName} 前缀下的变化。 每次变化时调用 Discover 获取最新实例列表并发送到返回的 channel。

type Option

type Option func(*Config)

Option etcd 配置的函数式选项。

func WithContainer

func WithContainer(ctn core.Container) Option

WithContainer 设置 IoC 容器实例。

func WithDialTimeout

func WithDialTimeout(timeout time.Duration) Option

WithDialTimeout 设置 etcd 客户端拨号超时时间。

func WithEndpoints

func WithEndpoints(endpoints ...string) Option

WithEndpoints 设置 etcd 集群地址列表。

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix 设置服务实例在 etcd 中的存储前缀。

func WithTLS

func WithTLS(tlsConfig *tls.Config) Option

WithTLS 设置 etcd 客户端 TLS 配置。

func WithTTL

func WithTTL(ttl time.Duration) Option

WithTTL 设置租约 TTL,即实例的心跳间隔。

Directories

Path Synopsis
Package etcd 提供 etcd 注册中心的自动配置。
Package etcd 提供 etcd 注册中心的自动配置。

Jump to

Keyboard shortcuts

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