Add example implementations for etcd, PostgreSQL, and Redis clients demonstrating automatic reconnection management and basic operations.
This commit is contained in:
65
examples/postgres_example.go
Normal file
65
examples/postgres_example.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/blueocean-go/reconnect"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// PostgreSQL连接字符串
|
||||
dsn := "host=localhost user=postgres password=postgres dbname=testdb sslmode=disable"
|
||||
|
||||
// 创建重连配置
|
||||
config := reconnect.DefaultConfig()
|
||||
config.RetryInterval = 3 * time.Second
|
||||
config.MaxRetries = 0 // 无限重试
|
||||
config.OnReconnect = func() {
|
||||
fmt.Println("PostgreSQL重连成功!")
|
||||
}
|
||||
config.OnDisconnect = func(err error) {
|
||||
fmt.Printf("PostgreSQL连接断开: %v\n", err)
|
||||
}
|
||||
|
||||
// 创建重连管理器
|
||||
manager := reconnect.PostgresManager(
|
||||
dsn,
|
||||
25, // maxConnections
|
||||
5, // maxIdleConnections
|
||||
30*time.Minute, // maxConnectionAge
|
||||
config,
|
||||
)
|
||||
|
||||
// 启动连接
|
||||
ctx := context.Background()
|
||||
if err := manager.Start(ctx); err != nil {
|
||||
log.Fatalf("启动失败: %v", err)
|
||||
}
|
||||
defer manager.Stop()
|
||||
|
||||
// 获取数据库连接并使用
|
||||
pgClient := reconnect.NewPostgresClient(dsn, 25, 5, 30*time.Minute)
|
||||
if err := pgClient.Connect(ctx); err != nil {
|
||||
log.Fatalf("连接失败: %v", err)
|
||||
}
|
||||
|
||||
db := pgClient.GetDB()
|
||||
if db == nil {
|
||||
log.Fatal("数据库连接为空")
|
||||
}
|
||||
|
||||
// 使用数据库连接
|
||||
var version string
|
||||
err := db.QueryRow("SELECT version()").Scan(&version)
|
||||
if err != nil {
|
||||
log.Printf("查询失败: %v", err)
|
||||
} else {
|
||||
fmt.Printf("PostgreSQL版本: %s\n", version)
|
||||
}
|
||||
|
||||
// 保持运行
|
||||
select {}
|
||||
}
|
||||
Reference in New Issue
Block a user