Files
wonder 6b1f071797 feat: init project with distributed lock implementation
- Add DistributedLock with Acquire/Release/Refresh using Lua scripts
- Add AcquireWithRetry with configurable retry interval and max retries
- Add integration tests for all lock operations
- Add .env for Redis connection (gitignored)
2026-05-29 19:19:01 +08:00

61 lines
1.2 KiB
Go

package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/joho/godotenv"
"github.com/redis/go-redis/v9"
"redis-rate-limiter/lock"
)
func main() {
// 加载 .env
if err := godotenv.Load(); err != nil {
log.Fatal("Error loading .env file")
}
// 连接 Redis
opt, err := redis.ParseURL(os.Getenv("REDIS_URL"))
if err != nil {
log.Fatalf("Invalid REDIS_URL: %v", err)
}
client := redis.NewClient(opt)
defer client.Close()
ctx := context.Background()
// 测试连接
if err := client.Ping(ctx).Err(); err != nil {
log.Fatalf("Redis connection failed: %v", err)
}
fmt.Println("✅ Redis connected")
// 示例:使用分布式锁
owner := fmt.Sprintf("instance-%d", time.Now().UnixNano())
l := lock.New(client, "my-resource-lock", owner, 10*time.Second)
// 尝试获取锁
acquired, err := l.Acquire(ctx)
if err != nil {
log.Fatalf("Acquire error: %v", err)
}
fmt.Printf("Lock acquired: %v\n", acquired)
if acquired {
// 模拟业务处理
fmt.Println("🔒 Holding lock, doing work...")
time.Sleep(2 * time.Second)
// 释放锁
if err := l.Release(ctx); err != nil {
log.Fatalf("Release error: %v", err)
}
fmt.Println("🔓 Lock released")
}
}