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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
| package main
import ( "context" "github.com/go-redis/redis/v8" "github.com/google/uuid" "log" "time" )
const ( unlockScript = ` if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end ` watchDogScript = ` if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("expire", KEYS[1], ARGV[2]) else return 0 end ` )
type RedisLock struct { client *redis.Client ctx context.Context cancel context.CancelFunc key string val string status bool expiration time.Duration waitTime time.Duration }
func NewRedisLock(ctx context.Context, client *redis.Client, key string, expiration time.Duration) *RedisLock { ctx, cancel := context.WithCancel(ctx) return &RedisLock{ ctx: ctx, client: client, cancel: cancel, key: key, val: time.Now().Format("20060102150405") + "_" + uuid.New().String(), expiration: expiration, waitTime: time.Second * 5, } }
func (lock *RedisLock) TryLock() (bool, error) { result, err := lock.Lock() if err != nil { return false, err } if result { lock.status = true go lock.WatchDog() } return result, nil }
func (lock *RedisLock) Lock() (bool, error) { now := time.Now() for time.Since(now) < lock.waitTime { result, err := lock.client.SetNX(lock.ctx, lock.key, lock.val, lock.expiration).Result() if err != nil { return false, err } if result { lock.status = true return true, nil } time.Sleep(time.Second) } return false, nil }
func (lock *RedisLock) UnLock() (bool, error) { if lock.status { result, err := lock.client.Eval(lock.ctx, unlockScript, []string{lock.key}, lock.val).Result() if err != nil { return false, err } lock.status = false lock.cancel() return result.(int64) == 1, nil } return true, nil }
func (lock *RedisLock) WatchDog() { loopTime := lock.expiration / 2 expiredTicker := time.NewTicker(loopTime) defer expiredTicker.Stop()
for { select { case <-lock.ctx.Done(): return case <-expiredTicker.C: log.Println("Extending lock...") _, err := lock.client.Eval(lock.ctx, watchDogScript, []string{lock.key}, lock.val, int(lock.expiration/time.Second)).Result() if err != nil { log.Println("Failed to extend lock:", err) return } } } }
func main() { client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, }) defer client.Close()
ctx := context.Background() lock := NewRedisLock(ctx, client, "my_lock", time.Second*10)
ok, err := lock.TryLock() if err != nil { log.Fatalf("Failed to acquire lock: %v", err) } if !ok { log.Println("Failed to acquire lock: lock is already held") return } log.Println("Lock acquired")
time.Sleep(9 * time.Second)
ok, err = lock.UnLock() if err != nil { log.Fatalf("Failed to release lock: %v", err) } if !ok { log.Println("Failed to release lock: lock is not held") } log.Println("Lock released")
}
|