/
distributed.go
64 lines (59 loc) · 1.15 KB
/
distributed.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package etcd
import (
"context"
"go.etcd.io/etcd/client/v3/concurrency"
)
/*
@File: distributed.go
@Author: khaosles
@Time: 2023/8/6 11:28
@Desc:
*/
// ExecOnceTask 基于分布式的唯一执行任务
func ExecOnceTask(key string, ttl int, task func()) error {
ctx := context.Background()
// 建立session
session, err := concurrency.NewSession(
Client,
concurrency.WithTTL(ttl),
concurrency.WithContext(ctx),
)
if err != nil {
return err
}
mutex := concurrency.NewMutex(session, key)
// 尝试获取锁
err = mutex.TryLock(ctx)
if err != nil {
return err
}
// 执行操作
task()
// 释放锁
_ = mutex.Unlock(ctx)
return nil
}
// ExecAllTask 基于分布式的全部执行任务
func ExecAllTask(key string, ttl int, task func()) error {
ctx := context.Background()
// 建立session
session, err := concurrency.NewSession(
Client,
concurrency.WithTTL(ttl),
concurrency.WithContext(ctx),
)
if err != nil {
return err
}
mutex := concurrency.NewMutex(session, key)
// 尝试获取锁
err = mutex.Lock(ctx)
if err != nil {
return err
}
// 执行操作
task()
// 释放锁
_ = mutex.Unlock(ctx)
return nil
}