• redis 分布式锁


    完整代码传送门

    package redis_distributed_lock
    
    import (
    	"context"
    	"fmt"
    	"redis-distributed-lock/redis_client"
    	"runtime"
    	"strings"
    	"time"
    
    	"github.com/redis/go-redis/v9"
    )
    
    type RedisDistributedLock struct {
    	client     *redis.Client
    	lockKey    string
    	lockValue  string
    	expireTime int
    }
    
    const redisLockKey = "redisLock"
    const redisLockExpireTime = 30
    
    func NewRedisDistributedLock(client *redis.Client) *RedisDistributedLock {
    	return &RedisDistributedLock{
    		client:     client,
    		lockKey:    redisLockKey,
    		lockValue:  GoID(),
    		expireTime: redisLockExpireTime,
    	}
    }
    
    func (r *RedisDistributedLock) Lock() {
    	script := `
    if redis.call("exists", KEYS[1]) == 0 or redis.call("hexists", KEYS[1], ARGV[1]) == 1 then
    	redis.call("hincrby", KEYS[1], ARGV[1], 1)
    	redis.call("expire", KEYS[1], ARGV[2])
    	return 1
    else
    	return 0
    end`
    	client := redis_client.NewClient()
    	for {
    		val, err := client.Eval(context.Background(), script, []string{r.lockKey}, r.lockValue, r.expireTime).Result()
    		if err != nil {
    			fmt.Printf("lock failed, err: %v\n", err)
    			return
    		}
    		if val != int64(1) {
    			time.Sleep(30 * time.Millisecond)
    		} else {
    			fmt.Printf("lock successfully, lockName: %v, lockValue: %v\n", r.lockKey, r.lockValue)
    			go r.renewExpire()
    			break
    		}
    	}
    }
    
    func (r *RedisDistributedLock) renewExpire() {
    	script := `
    if redis.call("hexists", KEYS[1], ARGV[1]) == 1 then
    	return redis.call("expire", KEYS[1], ARGV[2])
    else
    	return 0
    end`
    	for {
    		time.Sleep(time.Duration(r.expireTime/3) * time.Second)
    		val, err := r.client.Eval(context.Background(), script, []string{r.lockKey}, r.lockValue, r.expireTime).Result()
    		if err != nil {
    			fmt.Printf("renewExpire failed, err: %v\n", err)
    			return
    		}
    		if val == int64(0) {
    			return
    		}
    	}
    }
    
    func (r *RedisDistributedLock) Unlock() {
    	script := `
    if redis.call("hexists", KEYS[1], ARGV[1]) == 0 then
    	return nil
    elseif redis.call("hincrby", KEYS[1], ARGV[1], -1) == 0 then
    	return redis.call("del", KEYS[1])
    else
    	return 0
    end`
    	client := redis_client.NewClient()
    	val, err := client.Eval(context.Background(), script, []string{r.lockKey}, r.lockValue).Result()
    	if err != nil {
    		fmt.Printf("unlock failed, err: %v\n", err)
    		return
    	}
    	if val == redis.Nil {
    		fmt.Printf("lock does not exist\n")
    		return
    	}
    	fmt.Printf("unlock successfully, lockName: %v, lockValue: %v\n", r.lockKey, r.lockValue)
    }
    
    func GoID() string {
    	var buf [64]byte
    	n := runtime.Stack(buf[:], false)
    	return strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
    }
    
    
    • 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
  • 相关阅读:
    [Spring Cloud] Nacos 实战 + Aws云服务器
    为什么参与LiveVideoStackCon 2022 北京站
    Tomcat启动闪退问题解决方法
    深入理解 JVM 垃圾回收机制及其实现原理
    纯手工总结超详细关于计算机网络的五层知识点,看看你都掌握了没
    高性能系统架构设计之:多级缓存
    【STL】容器 - set和map的使用
    496. 下一个更大元素 I(javascript)496. Next Greater Element I
    Java线程安全问题
    秒杀:只出现一次的数字系列
  • 原文地址:https://blog.csdn.net/qq_44069788/article/details/134091704