consul

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: 9 Imported by: 0

README

go-boot-consul

Go Version License Build Status Go Reference Go Report Card

基于 go-boot 的 Consul 注册中心与配置中心集成模块。将 Consul 无缝集成到 go-boot 的 IoC 容器和自动配置体系中,提供服务注册、服务发现、健康检查和配置管理能力。

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

整体架构

┌───────────────────────────────────────────────────────────────────────┐
│                    go-boot ApplicationContext                         │
│  ┌───────────┐ ┌──────────────┐ ┌───────────┐ ┌───────────┐           │
│  │ Container │ │  Environment │ │ Lifecycle │ │ EventBus  │           │
│  └───────────┘ └──────────────┘ └───────────┘ └───────────┘           │
│                       ┌─────────────────────┐                         │
│                       │ AutoConfig Registry │                         │
│                       └─────────────────────┘                         │
└───────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
                    ┌───────────────────────────────┐
                    │    go-boot-consul Starter     │
                    │  ┌─────────────────────────┐  │
                    │  │ ConsulRegistry Bean     │  │
                    │  │ (center.Registry)       │  │
                    │  │ ConsulConfigCenter Bean │  │
                    │  │ (config.ConfigCenter)   │  │
                    │  │ Health Check & Watch    │  │
                    │  └─────────────────────────┘  │
                    └───────────────────────────────┘

目录

快速开始

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

# 安装 Consul 集成模块
go get github.com/xudefa/go-boot-consul
最小示例
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("consul.enabled", "true"),
        boot.WithProperty("consul.address", "127.0.0.1:8500"),
    )
    if err != nil {
        panic(err)
    }
    defer app.Stop()

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

    // 注册服务
    registry.Register(context.Background(), center.InstanceInfo{
        ServiceName: "my-service",
        ID:          "instance-001",
        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 接口
自动配置 通过 consul.enabled=true 自动启用
健康检查 支持 TTL 健康检查和 Health API 查询
阻塞查询 使用 Consul Blocking Query 实现长轮询 Watch
数据中心 支持多数据中心隔离
函数式选项 灵活的连接配置(Address、Datacenter、Token 等)

服务注册与发现

创建注册中心
registry, err := consul.NewConsulRegistry(
    consul.WithAddress("127.0.0.1:8500"),
    consul.WithDatacenter("dc1"),
    consul.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
consul:
  enabled: true
  address: "127.0.0.1:8500"
  config-center:
    enabled: true
    prefix: "config/my-app"
加载配置
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() 或配置文件设置:

配置项 默认值 说明
consul.enabled false 是否启用 Consul 注册中心
consul.address localhost:8500 Consul 服务端地址
consul.datacenter `` 数据中心(空则使用服务端默认)
consul.token `` ACL Token
consul.ttl 30s 健康检查 TTL
consul.config-center.enabled false 是否启用配置中心
consul.config-center.prefix config 配置 KV 前缀
示例配置
# application.yml
consul:
  enabled: true
  address: "127.0.0.1:8500"
  datacenter: "dc1"
  ttl: "30s"
  config-center:
    enabled: true
    prefix: "config/my-app"

项目结构

go-boot-consul/
├── consul.go              # ConsulRegistry 实现 center.Registry
├── consul_config.go       # 配置选项(Config, Option)
├── config_center.go       # ConsulConfigCenter 实现 config.ConfigCenter
├── autoconfig.go          # 自动配置注册
├── consul_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 consul 提供 Consul 配置中心实现

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

该包将 Consul 与 go-boot 服务发现和注册中心接口集成, 支持服务注册、发现和阻塞查询(Watch)。

定义:

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

快速开始:

// 创建 Consul 注册中心
registry, err := consul.NewConsulRegistry(
    consul.WithAddress("127.0.0.1:8500"),
)

// 注册服务
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 {
	Address    string
	Datacenter string
	Token      string
	TTL        time.Duration
	Container  core.Container
}

Config Consul 注册中心配置。

type ConsulConfigCenter

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

func NewConsulConfigCenter

func NewConsulConfigCenter(cfg *config.ConfigCenterConfig) (*ConsulConfigCenter, error)

func (*ConsulConfigCenter) Close

func (c *ConsulConfigCenter) Close() error

Close 关闭客户端

func (*ConsulConfigCenter) Load

Load 加载所有配置数据

func (*ConsulConfigCenter) Watch

func (c *ConsulConfigCenter) Watch(key string, callback func(config.ConfigData)) error

Watch 监控配置变更

type ConsulRegistry

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

ConsulRegistry 基于 Consul 实现的注册中心。 使用 Consul HTTP API 实现服务注册、发现和阻塞查询(Watch)。

func NewConsulRegistry

func NewConsulRegistry(opts ...Option) (*ConsulRegistry, error)

NewConsulRegistry 创建 Consul 注册中心实例。 支持通过 Option 配置地址、数据中心、Token 等参数。

func (*ConsulRegistry) Deregister

func (r *ConsulRegistry) Deregister(_ context.Context, info center.InstanceInfo) error

Deregister 从 Consul 注销指定服务实例。

func (*ConsulRegistry) Discover

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

Discover 发现指定服务的健康实例列表。 通过 Consul Health API 查询,仅返回通过健康检查的实例。

func (*ConsulRegistry) Register

func (r *ConsulRegistry) Register(_ context.Context, info center.InstanceInfo) error

Register 向 Consul 注册一个服务实例。 如果配置了 TTL,同时注册健康检查。 权重信息存储在 Meta["weight"] 中。

func (*ConsulRegistry) Watch

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

Watch 监听指定服务的实例变化。 使用 Consul 的阻塞查询(Blocking Query)实现长轮询, 通过 WaitIndex 增量获取变化。Watch 的返回结果与 Discover 完全一致。

type Option

type Option func(*Config)

Option Consul 配置的函数式选项。

func WithAddress

func WithAddress(addr string) Option

WithAddress 设置 Consul 服务器地址。

func WithContainer

func WithContainer(ctn core.Container) Option

WithContainer 设置 IoC 容器实例。

func WithDatacenter

func WithDatacenter(dc string) Option

WithDatacenter 设置 Consul 数据中心。

func WithTTL

func WithTTL(ttl time.Duration) Option

WithTTL 设置健康检查 TTL,即服务实例的心跳间隔。

func WithToken

func WithToken(token string) Option

WithToken 设置 Consul ACL Token。

Directories

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

Jump to

Keyboard shortcuts

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