更新一些option

This commit is contained in:
Yun
2025-09-17 19:41:47 +08:00
parent 7ceb13d438
commit 0a8589d7b6
2 changed files with 50 additions and 35 deletions
+32 -32
View File
@@ -31,43 +31,43 @@ var Redis *redis.Client
// Redis = client
// }
func TestLockx(t *testing.T) {
client := redis.NewClient(&redis.Options{
Addr: "127.0.0.1" + ":" + "6379",
Password: "123456", // no password set
DB: 0, // use default DB
})
if client == nil {
fmt.Println("redis init error")
return
}
fmt.Println("begin")
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// func TestLockx(t *testing.T) {
// client := redis.NewClient(&redis.Options{
// Addr: "127.0.0.1" + ":" + "6379",
// Password: "123456", // no password set
// DB: 0, // use default DB
// })
// if client == nil {
// fmt.Println("redis init error")
// return
// }
// fmt.Println("begin")
// ctx := context.Background()
// ctx, cancel := context.WithCancel(ctx)
// defer cancel()
wg := sync.WaitGroup{}
// wg := sync.WaitGroup{}
for i := 0; i < 20; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
lock, _ := lockx.NewGlobalLock(ctx, client, "lockx:test")
if b, _ := lock.Lock(); !b {
fmt.Println("lock error", i)
return
}
defer lock.Unlock()
// for i := 0; i < 20; i++ {
// wg.Add(1)
// go func(i int) {
// defer wg.Done()
// lock, _ := lockx.NewGlobalLock(ctx, client, "lockx:test")
// if b, _ := lock.Lock(); !b {
// fmt.Println("lock error", i)
// return
// }
// defer lock.Unlock()
fmt.Println("ssss2", i)
// fmt.Println("ssss2", i)
time.Sleep(time.Second * 2)
}(i)
time.Sleep(time.Second)
}
// time.Sleep(time.Second * 2)
// }(i)
// time.Sleep(time.Second)
// }
wg.Wait()
}
// wg.Wait()
// }
// MockLogger 用于测试的模拟日志器
type MockLogger struct {
+16 -1
View File
@@ -8,10 +8,13 @@ import (
type option struct {
lockTimeout time.Duration // 锁的超时时间
Expiry time.Duration // 单次刷新有效时间
MaxRetryTimes int // 尝试次数
RetryInterval time.Duration // 尝试间隔
Expiry time.Duration // 单次刷新有效时间
RefreshPeriod time.Duration // 刷新间隔
logger Logger // 日志
}
@@ -35,36 +38,48 @@ func InitOption(opts ...Option) {
type Option func(*option)
// 最大锁定时间(默认1h)
func WithLockTimeout(t time.Duration) Option {
return func(o *option) {
o.lockTimeout = t
}
}
// 日志
func WithLogger(logger Logger) Option {
return func(o *option) {
o.logger = logger
}
}
// key有效时间(会自动刷新)
func WithExpiry(expiry time.Duration) Option {
return func(o *option) {
o.Expiry = expiry
if o.Expiry/3 < o.RefreshPeriod {
o.RefreshPeriod = o.Expiry / 3
}
}
}
// 刷新间隔
func WithRefreshPeriod(period time.Duration) Option {
return func(o *option) {
o.RefreshPeriod = period
if o.RefreshPeriod*3 > o.Expiry {
o.Expiry = o.RefreshPeriod * 3
}
}
}
// 最大尝试次数
func WithMaxRetryTimes(times int) Option {
return func(o *option) {
o.MaxRetryTimes = times
}
}
// 尝试间隔
func WithRetryInterval(interval time.Duration) Option {
return func(o *option) {
o.RetryInterval = interval