nacos

package module
v1.0.3 Latest Latest
Warning

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

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

README

go-boot-nacos

Go Version License Build Status Go Reference Go Report Card

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

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

整体架构

┌───────────────────────────────────────────────────────────────────────┐
│                    go-boot ApplicationContext                         │
│  ┌───────────┐ ┌──────────────┐ ┌───────────┐ ┌───────────┐           │
│  │ Container │ │  Environment │ │ Lifecycle │ │ EventBus  │           │
│  └───────────┘ └──────────────┘ └───────────┘ └───────────┘           │
│                       ┌─────────────────────┐                         │
│                       │ AutoConfig Registry │                         │
│                       └─────────────────────┘                         │
└───────────────────────────────────────────────────────────────────────┘
                                    │
                                    ▼
                    ┌───────────────────────────────┐
                    │    go-boot-nacos Starter      │
                    │  ┌─────────────────────────┐  │
                    │  │ NacosRegistry Bean      │  │
                    │  │ (center.Registry)       │  │
                    │  │ NacosConfigCenter Bean  │  │
                    │  │ (config.ConfigCenter)   │  │
                    │  │ Naming & Config Client  │  │
                    │  └─────────────────────────┘  │
                    └───────────────────────────────┘

目录

快速开始

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

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

    // 获取注册中心(自动注入)
    registry := app.Container().Get("nacosRegistry").(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 接口
自动配置 通过 nacos.enabled=true 自动启用
命名空间 支持 Nacos Namespace 隔离
分组管理 支持 Group 分组管理服务和配置
服务订阅 支持 Subscribe/Unsubscribe 监听实例变化
配置监听 支持配置变更的实时监听
函数式选项 灵活的连接配置(Address、Namespace、Group 等)

服务注册与发现

创建注册中心
registry, err := nacos.NewNacosRegistry(
    nacos.WithAddress("127.0.0.1:8848"),
    nacos.WithNamespace("dev"),
    nacos.WithGroup("DEFAULT_GROUP"),
)
注册服务
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
nacos:
  enabled: true
  address: "127.0.0.1:8848"
  config-center:
    enabled: true
    data-id: "app-config.yaml"
    group: "DEFAULT_GROUP"
加载配置
configCenter := app.Container().Get("configCenter").(config.ConfigCenter)
data, err := configCenter.Load()
监听配置变更
configCenter.Watch("app-config.yaml", func(data config.ConfigData) {
    fmt.Printf("配置已更新: %v\n", data)
})

配置选项

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

配置项 默认值 说明
nacos.enabled false 是否启用 Nacos 注册中心
nacos.address localhost:8848 Nacos 服务端地址
nacos.namespace `` 命名空间 ID
nacos.group DEFAULT_GROUP 服务分组
nacos.log-level info 日志级别(debug/info/warn/error)
nacos.config-center.enabled false 是否启用配置中心
nacos.config-center.data-id app-config 配置 DataID
nacos.config-center.group DEFAULT_GROUP 配置分组
示例配置
# application.yml
nacos:
  enabled: true
  address: "127.0.0.1:8848"
  namespace: "dev"
  group: "DEFAULT_GROUP"
  log-level: "info"
  config-center:
    enabled: true
    data-id: "my-app.yaml"
    group: "DEFAULT_GROUP"

项目结构

go-boot-nacos/
├── nacos.go              # NacosRegistry 实现 center.Registry
├── nacos_config.go       # 配置选项(Config, Option)
├── config_center.go      # NacosConfigCenter 实现 config.ConfigCenter
├── autoconfig.go         # 自动配置注册
├── nacos_test.go         # 单元测试
├── config_center_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 nacos 提供 Nacos 配置中心实现

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

该包将 Nacos 与 go-boot 服务发现和注册中心接口集成, 使用 Nacos 官方 SDK 实现服务注册、发现和订阅。

定义:

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

快速开始:

// 创建 Nacos 注册中心
registry, err := nacos.NewNacosRegistry(
    nacos.WithAddress("127.0.0.1:8848"),
)

// 注册服务
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
	NamespaceID       string
	Group             string
	LogLevel          string
	Timeout           time.Duration
	HeartbeatInterval time.Duration
	Container         core.Container
}

Config Nacos 注册中心配置。

type NacosConfigCenter

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

func NewNacosConfigCenter

func NewNacosConfigCenter(cfg *config.ConfigCenterConfig) (*NacosConfigCenter, error)

func (*NacosConfigCenter) Close

func (n *NacosConfigCenter) Close() error

Close 关闭客户端

func (*NacosConfigCenter) Load

Load 加载所有配置数据

func (*NacosConfigCenter) Watch

func (n *NacosConfigCenter) Watch(key string, callback func(config.ConfigData)) error

Watch 监控配置变更

type NacosRegistry

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

NacosRegistry 基于 Nacos 实现的注册中心。 使用 Nacos 官方 SDK 实现服务注册、发现和订阅。

func NewNacosRegistry

func NewNacosRegistry(opts ...Option) (*NacosRegistry, error)

NewNacosRegistry 创建 Nacos 注册中心实例。 支持通过 Option 配置地址、命名空间、分组、日志级别等参数。

func (*NacosRegistry) Deregister

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

Deregister 从 Nacos 中注销指定服务实例。

func (*NacosRegistry) Discover

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

Discover 发现指定服务的所有健康实例。

func (*NacosRegistry) Register

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

Register 向 Nacos 注册一个服务实例。

func (*NacosRegistry) Watch

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

Watch 监听指定服务的实例变化。 内部调用 Nacos Subscribe 注册回调,当实例列表变化时通过返回的 channel 通知。 当 context 被取消时,自动调用 Unsubscribe 清理订阅。

type Option

type Option func(*Config)

Option Nacos 配置的函数式选项。

func WithAddress

func WithAddress(addr string) Option

WithAddress 设置 Nacos 服务器地址。

func WithContainer

func WithContainer(ctn core.Container) Option

WithContainer 设置 IoC 容器实例。

func WithGroup

func WithGroup(group string) Option

WithGroup 设置 Nacos 分组名称。

func WithHeartbeatInterval

func WithHeartbeatInterval(interval time.Duration) Option

WithHeartbeatInterval 设置实例心跳间隔。

func WithLogLevel

func WithLogLevel(level string) Option

WithLogLevel 设置 Nacos 客户端日志级别。

func WithNamespace

func WithNamespace(namespaceID string) Option

WithNamespace 设置 Nacos 命名空间 ID。

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout 设置 Nacos 客户端请求超时时间。

Directories

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

Jump to

Keyboard shortcuts

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