Documentation
¶
Overview ¶
Package connector 为 Genesis 提供统一的连接管理能力。
核心特性:
- 统一抽象:通过 Connector 接口提供一致的连接管理 API
- 类型安全:通过 TypedConnector[T] 泛型接口确保编译时类型检查
- 多数据源支持:Redis、MySQL、PostgreSQL、SQLite、Etcd、NATS、Kafka
- 健康检查:提供主动探活和缓存态读取,但不负责统一重连或故障恢复
- 并发安全:所有公开方法均为并发安全,支持多协程同时访问
- 资源管理:遵循"谁创建,谁负责释放"原则,Close() 应在应用层调用
设计理念:
- 接口优先:定义清晰的接口契约,实现细节可替换
- 显式依赖注入:通过构造函数注入依赖,避免全局状态
- 幂等连接:Connect() 方法可安全重复调用
- 延迟连接:NewXXX() 创建连接器但不立即建立连接,Connect() 时才连接
基本使用:
cfg := &connector.RedisConfig{
Addr: "127.0.0.1:6379",
Password: "",
DB: 0,
}
conn, err := connector.NewRedis(cfg, connector.WithLogger(logger))
if err != nil {
panic(err)
}
defer conn.Close()
// 建立连接(幂等,可多次调用)
if err := conn.Connect(ctx); err != nil {
panic(err)
}
// 获取类型安全的客户端
client := conn.GetClient()
result, err := client.Get(ctx, "key").Result()
资源所有权:
Connector 拥有底层连接的生命周期,应通过 defer 确保 Close() 被调用。 Component(如 cache、dlock)仅借用 Connector,不应调用 Close()。 应用层应按照 LIFO 顺序释放资源:先关闭依赖 Connector 的组件,再关闭 Connector。
Index ¶
- Variables
- type Connector
- type EtcdConfig
- type EtcdConnector
- type KafkaConfig
- type KafkaConnector
- type MySQLConfig
- type MySQLConnector
- type NATSConfig
- type NATSConnector
- type Option
- type PostgreSQLConfig
- type PostgreSQLConnector
- type RedisConfig
- type RedisConnector
- type SQLiteConfig
- type SQLiteConnector
- type TypedConnector
Constants ¶
This section is empty.
Variables ¶
var ( // ErrConnection 连接建立失败 ErrConnection = xerrors.New("connector: connection failed") // ErrConfig 配置无效 ErrConfig = xerrors.New("connector: invalid config") // ErrHealthCheck 健康检查失败 ErrHealthCheck = xerrors.New("connector: health check failed") // ErrClientNil 客户端为空(未初始化或已关闭) ErrClientNil = xerrors.New("connector: client is nil") )
Sentinel Errors - 连接器专用的哨兵错误
Functions ¶
This section is empty.
Types ¶
type Connector ¶
type Connector interface {
// Connect 建立连接。
//
// 此方法是幂等的,可安全多次调用。首次调用时建立连接,
// 后续调用直接返回 nil。连接过程阻塞直到成功或失败。
//
// 返回错误:
// - ErrConnection: 连接建立失败
// - ErrConfig: 配置无效
Connect(ctx context.Context) error
// Close 关闭连接并释放资源。
//
// 此方法是幂等的,可安全多次调用。关闭后,
// GetClient() 将返回 nil,HealthCheck() 将返回 ErrClientNil。
//
// 重要:应在应用层通过 defer 确保调用,遵循"谁创建,谁负责释放"原则。
Close() error
// HealthCheck 检查连接健康状态。
//
// 通过发送测试请求验证连接可用性。此方法会更新内部健康状态缓存,
// 可通过 IsHealthy() 快速读取。
//
// 返回错误:
// - ErrClientNil: 客户端未初始化或已关闭
// - ErrHealthCheck: 健康检查失败
HealthCheck(ctx context.Context) error
// IsHealthy 返回缓存的健康状态。
//
// 此方法无阻塞,直接返回最后一次 HealthCheck() 的结果。
// 对于实时健康检查,应使用 HealthCheck() 方法。
IsHealthy() bool
// Name 返回连接实例名称。
//
// 名称用于日志记录和指标标识,应在配置中唯一标识此连接器实例。
Name() string
}
Connector 定义所有连接器的通用行为。
所有连接器必须实现此接口,确保一致的连接管理体验。 接口方法均为并发安全,可从多个协程同时调用。
type EtcdConfig ¶
type EtcdConfig struct {
// 基础配置
Name string `mapstructure:"name" json:"name" yaml:"name"` // 连接器名称 (默认: "default")
// 核心配置
Endpoints []string `mapstructure:"endpoints" json:"endpoints" yaml:"endpoints"` // 连接地址列表 (必填)
Username string `mapstructure:"username" json:"username" yaml:"username"` // 认证用户 (可选)
Password string `mapstructure:"password" json:"password" yaml:"password"` // 认证密码 (可选)
// 高级配置
DialTimeout time.Duration `mapstructure:"dial_timeout" json:"dial_timeout" yaml:"dial_timeout"` // 连接超时 (默认: 5s)
KeepAliveTime time.Duration `mapstructure:"keep_alive_time" json:"keep_alive_time" yaml:"keep_alive_time"` // 心跳间隔 (默认: 10s)
KeepAliveTimeout time.Duration `mapstructure:"keep_alive_timeout" json:"keep_alive_timeout" yaml:"keep_alive_timeout"` // 心跳超时 (默认: 3s)
}
EtcdConfig Etcd连接配置
type EtcdConnector ¶
type EtcdConnector interface {
TypedConnector[*clientv3.Client]
}
EtcdConnector Etcd 连接器接口。
提供对 Etcd 键值存储的连接管理,支持分布式锁、配置中心、服务发现等场景。
func NewEtcd ¶
func NewEtcd(cfg *EtcdConfig, opts ...Option) (EtcdConnector, error)
NewEtcd 创建 Etcd 连接器 注意:实际连接在调用 Connect() 时建立
type KafkaConfig ¶
type KafkaConfig struct {
// 基础配置
Name string `mapstructure:"name" json:"name" yaml:"name"` // 连接器名称 (默认: "default")
// 核心配置
Seed []string `mapstructure:"seed" json:"seed" yaml:"seed"` // 初始连接节点 (必填)
// 认证配置
User string `mapstructure:"user" json:"user" yaml:"user"` // SASL 用户名 (可选)
Password string `mapstructure:"password" json:"password" yaml:"password"` // SASL 密码 (可选)
ClientID string `mapstructure:"client_id" json:"client_id" yaml:"client_id"` // 客户端 ID (默认: "genesis-connector")
// 连接配置
ConnectTimeout time.Duration `mapstructure:"connect_timeout" json:"connect_timeout" yaml:"connect_timeout"` // 连接超时 (默认: 10s)
RequestTimeout time.Duration `mapstructure:"request_timeout" json:"request_timeout" yaml:"request_timeout"` // 请求超时 (默认: 10s)
AllowAutoTopicCreate bool `mapstructure:"allow_auto_topic_create" json:"allow_auto_topic_create" yaml:"allow_auto_topic_create"` // 允许自动创建 Topic (默认: false)
}
KafkaConfig Kafka连接配置
type KafkaConnector ¶
type KafkaConnector interface {
TypedConnector[*kgo.Client]
}
KafkaConnector Kafka 连接器接口。
提供对 Kafka 消息队列的连接管理,支持高吞吐的消息生产和消费。 基于 franz-go 客户端,提供现代的 Kafka 消费者组 API。
func NewKafka ¶
func NewKafka(cfg *KafkaConfig, opts ...Option) (KafkaConnector, error)
NewKafka 创建 Kafka 连接器 注意:实际连接在调用 Connect() 时建立
type MySQLConfig ¶
type MySQLConfig struct {
// 基础配置
Name string `mapstructure:"name" json:"name" yaml:"name"` // 连接器名称 (默认: "default")
// 核心配置
DSN string `mapstructure:"dsn" json:"dsn" yaml:"dsn"` // 完整 DSN (可选,若提供则忽略 Host/Port 等,优先级最高)
Host string `mapstructure:"host" json:"host" yaml:"host"` // 主机地址 (DSN 未设置时必填)
Port int `mapstructure:"port" json:"port" yaml:"port"` // 端口 (默认: 3306)
Username string `mapstructure:"username" json:"username" yaml:"username"` // 用户名 (DSN 未设置时必填)
Password string `mapstructure:"password" json:"password" yaml:"password"` // 密码
Database string `mapstructure:"database" json:"database" yaml:"database"` // 数据库名 (DSN 未设置时必填)
// 高级配置
Charset string `mapstructure:"charset" json:"charset" yaml:"charset"` // 字符集 (默认: "utf8mb4")
MaxIdleConns int `mapstructure:"max_idle_conns" json:"max_idle_conns" yaml:"max_idle_conns"` // 最大空闲连接数 (默认: 10)
MaxOpenConns int `mapstructure:"max_open_conns" json:"max_open_conns" yaml:"max_open_conns"` // 最大打开连接数 (默认: 100)
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime" json:"conn_max_lifetime" yaml:"conn_max_lifetime"` // 连接最大生命周期 (默认: 1h)
ConnectTimeout time.Duration `mapstructure:"connect_timeout" json:"connect_timeout" yaml:"connect_timeout"` // 连接超时 (默认: 5s)
}
MySQLConfig MySQL连接配置
type MySQLConnector ¶
type MySQLConnector interface {
TypedConnector[*gorm.DB]
}
MySQLConnector MySQL 连接器接口。
提供对 MySQL 数据库的连接管理,基于 GORM ORM 框架。 支持连接池、预处理缓存、自动重连等特性。
func NewMySQL ¶
func NewMySQL(cfg *MySQLConfig, opts ...Option) (MySQLConnector, error)
NewMySQL 创建 MySQL 连接器 注意:实际连接在调用 Connect() 时建立
type NATSConfig ¶
type NATSConfig struct {
// 基础配置
Name string `mapstructure:"name" json:"name" yaml:"name"` // 连接器名称 (默认: "default")
// 核心配置
URL string `mapstructure:"url" json:"url" yaml:"url"` // 连接地址 (必填),如 "nats://127.0.0.1:4222"
Username string `mapstructure:"username" json:"username" yaml:"username"` // 用户名 (可选)
Password string `mapstructure:"password" json:"password" yaml:"password"` // 密码 (可选)
Token string `mapstructure:"token" json:"token" yaml:"token"` // 令牌 (可选)
// 高级配置
ConnectTimeout time.Duration `mapstructure:"connect_timeout" json:"connect_timeout" yaml:"connect_timeout"` // 连接超时 (默认: 5s)
MaxReconnects int `mapstructure:"max_reconnects" json:"max_reconnects" yaml:"max_reconnects"` // 最大重连次数 (默认: 60)
ReconnectWait time.Duration `mapstructure:"reconnect_wait" json:"reconnect_wait" yaml:"reconnect_wait"` // 重连等待时间 (默认: 2s)
PingInterval time.Duration `mapstructure:"ping_interval" json:"ping_interval" yaml:"ping_interval"` // ping间隔 (默认: 2m)
}
NATSConfig NATS连接配置
type NATSConnector ¶
type NATSConnector interface {
TypedConnector[*nats.Conn]
}
NATSConnector NATS 连接器接口。
提供对 NATS 消息系统的连接管理,支持发布订阅、请求响应、消息队列等模式。 内置自动重连机制,网络故障时会自动尝试恢复连接。
func NewNATS ¶
func NewNATS(cfg *NATSConfig, opts ...Option) (NATSConnector, error)
NewNATS 创建 NATS 连接器 注意:实际连接在调用 Connect() 时建立
type PostgreSQLConfig ¶
type PostgreSQLConfig struct {
// 基础配置
Name string `mapstructure:"name" json:"name" yaml:"name"` // 连接器名称 (默认: "default")
// 核心配置
DSN string `mapstructure:"dsn" json:"dsn" yaml:"dsn"` // 完整 DSN (可选,若提供则忽略 Host/Port 等,优先级最高)
Host string `mapstructure:"host" json:"host" yaml:"host"` // 主机地址 (DSN 未设置时必填)
Port int `mapstructure:"port" json:"port" yaml:"port"` // 端口 (默认: 5432)
Username string `mapstructure:"username" json:"username" yaml:"username"` // 用户名 (DSN 未设置时必填)
Password string `mapstructure:"password" json:"password" yaml:"password"` // 密码
Database string `mapstructure:"database" json:"database" yaml:"database"` // 数据库名 (DSN 未设置时必填)
// 高级配置
SSLMode string `mapstructure:"sslmode" json:"sslmode" yaml:"sslmode"` // SSL 模式 (默认: "disable")
MaxIdleConns int `mapstructure:"max_idle_conns" json:"max_idle_conns" yaml:"max_idle_conns"` // 最大空闲连接数 (默认: 10)
MaxOpenConns int `mapstructure:"max_open_conns" json:"max_open_conns" yaml:"max_open_conns"` // 最大打开连接数 (默认: 100)
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime" json:"conn_max_lifetime" yaml:"conn_max_lifetime"` // 连接最大生命周期 (默认: 1h)
ConnectTimeout time.Duration `mapstructure:"connect_timeout" json:"connect_timeout" yaml:"connect_timeout"` // 连接超时 (默认: 5s)
Timezone string `mapstructure:"timezone" json:"timezone" yaml:"timezone"` // 时区 (默认: "UTC")
}
PostgreSQLConfig PostgreSQL连接配置
type PostgreSQLConnector ¶
type PostgreSQLConnector interface {
TypedConnector[*gorm.DB]
}
PostgreSQLConnector PostgreSQL 连接器接口。
提供对 PostgreSQL 数据库的连接管理,基于 GORM ORM 框架。 支持高级数据类型(JSONB、ARRAY、GIS)、复杂查询、全文搜索等企业级特性。
func NewPostgreSQL ¶
func NewPostgreSQL(cfg *PostgreSQLConfig, opts ...Option) (PostgreSQLConnector, error)
NewPostgreSQL 创建 PostgreSQL 连接器 注意:实际连接在调用 Connect() 时建立
type RedisConfig ¶
type RedisConfig struct {
// 基础配置
Name string `mapstructure:"name" json:"name" yaml:"name"` // 连接器名称 (默认: "default")
// 核心配置
Addr string `mapstructure:"addr" json:"addr" yaml:"addr"` // 连接地址 (必填),如 "127.0.0.1:6379"
Password string `mapstructure:"password" json:"password" yaml:"password"` // 认证密码 (可选)
DB int `mapstructure:"db" json:"db" yaml:"db"` // 数据库编号 (默认: 0)
// 高级配置
PoolSize int `mapstructure:"pool_size" json:"pool_size" yaml:"pool_size"` // 连接池大小 (默认: 10)
MinIdleConns int `mapstructure:"min_idle_conns" json:"min_idle_conns" yaml:"min_idle_conns"` // 最小空闲连接数 (默认: 5)
DialTimeout time.Duration `mapstructure:"dial_timeout" json:"dial_timeout" yaml:"dial_timeout"` // 连接超时 (默认: 5s)
ReadTimeout time.Duration `mapstructure:"read_timeout" json:"read_timeout" yaml:"read_timeout"` // 读取超时 (默认: 3s)
WriteTimeout time.Duration `mapstructure:"write_timeout" json:"write_timeout" yaml:"write_timeout"` // 写入超时 (默认: 3s)
// 可观测性
EnableTracing bool `mapstructure:"enable_tracing" json:"enable_tracing" yaml:"enable_tracing"` // 是否启用 Tracing (透传给 redisotel)
}
RedisConfig Redis连接配置
type RedisConnector ¶
type RedisConnector interface {
TypedConnector[*redis.Client]
}
RedisConnector Redis 连接器接口。
提供对 Redis 服务器的连接管理,支持连接池、Pipeline、事务等特性。
func NewRedis ¶
func NewRedis(cfg *RedisConfig, opts ...Option) (RedisConnector, error)
NewRedis 创建 Redis 连接器 注意:实际连接在调用 Connect() 时建立
type SQLiteConfig ¶
type SQLiteConfig struct {
// 基础配置
Name string `mapstructure:"name" json:"name" yaml:"name"` // 连接器名称 (默认: "default")
// 核心配置
Path string `mapstructure:"path" json:"path" yaml:"path"` // 数据库文件路径 (必填),如 "./test.db" 或 "file::memory:?cache=shared"
}
SQLiteConfig SQLite连接配置
type SQLiteConnector ¶
type SQLiteConnector interface {
TypedConnector[*gorm.DB]
}
SQLiteConnector SQLite 连接器接口。
提供对 SQLite 数据库的连接管理,基于 GORM ORM 框架。 支持内存数据库和文件数据库,适合测试和嵌入式场景。
func NewSQLite ¶
func NewSQLite(cfg *SQLiteConfig, opts ...Option) (SQLiteConnector, error)
NewSQLite 创建 SQLite 连接器 注意:实际连接在调用 Connect() 时建立
type TypedConnector ¶
type TypedConnector[T any] interface { Connector // GetClient 返回底层客户端实例。 // // 调用者应通过此客户端执行实际的数据操作。 // 注意:在 Connect() 之前或 Close() 之后调用可能返回 nil。 GetClient() T }
TypedConnector 提供类型安全的客户端访问。
此接口组合了 Connector 基础接口,并添加了 GetClient() 方法 用于获取特定类型的客户端。所有具体连接器接口都应基于此定义。
类型参数 T 是客户端类型,如 *redis.Client、*gorm.DB 等。