Add example implementations for etcd, PostgreSQL, and Redis clients demonstrating automatic reconnection management and basic operations.
This commit is contained in:
70
examples/redis_example.go
Normal file
70
examples/redis_example.go
Normal 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 {}
|
||||
}
|
||||
Reference in New Issue
Block a user