feat: add lock

Browse Source
main
git 2024-05-25 00:41:28 +08:00
parent 13675c3e86
commit 0749384c84
Signed by: git
GPG Key ID: 3F65EFFA44207ADD
2 changed files with 22 additions and 17 deletions

View File

@ -80,7 +80,7 @@ func startServer() (*machinery.Server, error) {
}
// lock := redislock.New(cnf, []string{"localhost:6379"}, 3, 2)
lock, err := etcdlock.New(cnf, "http://127.0.0.1:2379", 3)
lock, err := etcdlock.New(context.Background(), "http://127.0.0.1:2379", 3)
if err != nil {
return nil, err
}

View File

@ -7,7 +7,6 @@ import (
"strings"
"time"
"github.com/RichardKnop/machinery/v2/config"
"github.com/RichardKnop/machinery/v2/locks/iface"
"github.com/RichardKnop/machinery/v2/log"
clientv3 "go.etcd.io/etcd/client/v3"
@ -15,49 +14,55 @@ import (
)
var (
ErrRedisLockFailed = errors.New("redis lock: failed to acquire lock")
// ErrLockFailed ..
ErrLockFailed = errors.New("etcd lock: failed to acquire lock")
)
type etcdLock struct {
globalConf *config.Config
conf clientv3.Config
cli *clientv3.Client
retries int
cli *clientv3.Client
retries int
}
func New(cnf *config.Config, endpoint string, retries int) (iface.Lock, error) {
etcdConf := clientv3.Config{Endpoints: []string{endpoint}}
// New ..
func New(ctx context.Context, endpoint string, retries int) (iface.Lock, error) {
etcdConf := clientv3.Config{
Endpoints: []string{endpoint},
Context: ctx,
DialTimeout: time.Second * 5,
}
cli, err := clientv3.New(etcdConf)
if err != nil {
return nil, err
}
lock := etcdLock{
globalConf: cnf,
conf: etcdConf,
cli: cli,
retries: retries,
cli: cli,
retries: retries,
}
return &lock, nil
}
// LockWithRetries ..
func (r etcdLock) LockWithRetries(key string, unixTsToExpireNs int64) error {
for i := 0; i < r.retries; i++ {
i := 0
for ; i < r.retries; i++ {
err := r.Lock(key, unixTsToExpireNs)
if err == nil {
// 成功拿到锁,返回
return nil
}
log.INFO.Printf("acquired lock=%s failed, retries=%d, err=%s", key, i, err)
log.DEBUG.Printf("acquired lock=%s failed, retries=%d, err=%s", key, i, err)
time.Sleep(time.Millisecond * 100)
}
return ErrRedisLockFailed
log.INFO.Printf("acquired lock=%s failed, retries=%d", key, i)
return ErrLockFailed
}
// Lock ..
func (r etcdLock) Lock(key string, unixTsToExpireNs int64) error {
now := time.Now().UnixNano()
ttl := time.Duration(unixTsToExpireNs + 1 - now)