Add example implementations for etcd, PostgreSQL, and Redis clients demonstrating automatic reconnection management and basic operations.

This commit is contained in:
2025-12-12 15:49:00 +08:00
parent 597e1cf840
commit c68b77b1b7
3 changed files with 208 additions and 0 deletions

70
examples/redis_example.go Normal file
View File

@@ -0,0 +1,70 @@
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/blueocean-go/reconnect"
"github.com/redis/go-redis/v9"
)
func main() {
// 创建Redis选项
options := &redis.Options{
Addr: "localhost:6379",
Password: "", // 无密码
DB: 0,
}
// 创建重连配置
config := reconnect.DefaultConfig()
config.RetryInterval = 3 * time.Second
config.MaxRetries = 0 // 无限重试
config.OnReconnect = func() {
fmt.Println("Redis重连成功!")
}
config.OnDisconnect = func(err error) {
fmt.Printf("Redis连接断开: %v\n", err)
}
// 创建重连管理器
manager := reconnect.RedisManager(options, config)
// 启动连接
ctx := context.Background()
if err := manager.Start(ctx); err != nil {
log.Fatalf("启动失败: %v", err)
}
defer manager.Stop()
// 获取Redis客户端并使用
redisClient := reconnect.NewRedisClient(options)
if err := redisClient.Connect(ctx); err != nil {
log.Fatalf("连接失败: %v", err)
}
client := redisClient.GetClient()
if client == nil {
log.Fatal("客户端为空")
}
// 使用Redis客户端
err := client.Set(ctx, "key", "value", 0).Err()
if err != nil {
log.Printf("设置键值失败: %v", err)
} else {
fmt.Println("设置键值成功")
}
val, err := client.Get(ctx, "key").Result()
if err != nil {
log.Printf("获取键值失败: %v", err)
} else {
fmt.Printf("获取键值: %s\n", val)
}
// 保持运行
select {}
}