初始化 zhub Go 客户端项目
新增 zhub 客户端完整实现,包括配置加载、TCP通信、消息发布/订阅、 RPC 调用、分布式锁等功能。支持从项目配置文件、环境变量等多种方式初始化客户端,并提供便捷的全局调用接口。- 添加 `.gitignore` 忽略 IDE 和临时文件 - 实现 `api.go` 提供全局便捷方法封装客户端调用 - 实现 `client.go` 核心客户端逻辑,包含网络通信、消息处理等 - 添加 `client_test.go` 单元测试和集成测试示例 - 实现 `config.go` 支持灵活的配置加载机制 - 添加示例配置文件 `example-config.yml` - 初始化 Go 模块依赖 `go.mod` 和 `go.sum` - 实现 `init.go` 提供多种初始化方式 - 添加 MIT 许可证文件 `LICENSE` - 新增使用示例 `example/main.go` 展示基本功能调用 - 实现 `manager.go` 管理默认客户端实例及初始化逻辑
This commit is contained in:
92
manager.go
Normal file
92
manager.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package zhub
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Client 客户端包装器
|
||||
type Client struct {
|
||||
*ZHubClient
|
||||
config *Config
|
||||
}
|
||||
|
||||
var (
|
||||
defaultClient *Client
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// InitWithOptions 使用选项初始化默认客户端
|
||||
func InitWithOptions(opts *ConfigOptions) error {
|
||||
var err error
|
||||
once.Do(func() {
|
||||
config, configErr := LoadConfigWithOptions(opts)
|
||||
if configErr != nil {
|
||||
err = fmt.Errorf("failed to load config: %w", configErr)
|
||||
return
|
||||
}
|
||||
|
||||
client, clientErr := NewClient(config)
|
||||
if clientErr != nil {
|
||||
err = fmt.Errorf("failed to create client: %w", clientErr)
|
||||
return
|
||||
}
|
||||
|
||||
defaultClient = client
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// InitWithProjectConfig 使用项目配置文件初始化
|
||||
func InitWithProjectConfig(projectConfigPath string) error {
|
||||
opts := &ConfigOptions{
|
||||
ConfigPath: projectConfigPath,
|
||||
ConfigKey: "zhub",
|
||||
}
|
||||
return InitWithOptions(opts)
|
||||
}
|
||||
|
||||
// NewClient 创建新的客户端实例
|
||||
func NewClient(config *Config) (*Client, error) {
|
||||
client := &Client{
|
||||
ZHubClient: &ZHubClient{
|
||||
Appname: config.Appname,
|
||||
Addr: config.Addr,
|
||||
Groupid: config.Groupid,
|
||||
Auth: config.Auth,
|
||||
},
|
||||
config: config,
|
||||
}
|
||||
|
||||
err := client.Start()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// DefaultClient 获取默认客户端实例
|
||||
func DefaultClient() *Client {
|
||||
if defaultClient == nil {
|
||||
log.Panic("zhub client not initialized, call InitWithProjectConfig() first")
|
||||
}
|
||||
return defaultClient
|
||||
}
|
||||
|
||||
// GetClient 获取客户端实例(如果未初始化则使用默认配置)
|
||||
func GetClient() *Client {
|
||||
if defaultClient == nil {
|
||||
// 尝试从当前目录加载默认配置
|
||||
opts := &ConfigOptions{
|
||||
ConfigName: "app",
|
||||
ConfigType: "yml",
|
||||
ConfigKey: "zhub",
|
||||
}
|
||||
if err := InitWithOptions(opts); err != nil {
|
||||
log.Panic("Failed to initialize zhub client:", err)
|
||||
}
|
||||
}
|
||||
return defaultClient
|
||||
}
|
||||
Reference in New Issue
Block a user