|
| 1 | +package me.chanjar.weixin.common.util.locks; |
| 2 | + |
| 3 | +import lombok.Getter; |
| 4 | +import lombok.NonNull; |
| 5 | +import org.jetbrains.annotations.NotNull; |
| 6 | +import org.springframework.dao.DataAccessException; |
| 7 | +import org.springframework.data.redis.connection.RedisConnection; |
| 8 | +import org.springframework.data.redis.connection.RedisStringCommands; |
| 9 | +import org.springframework.data.redis.core.RedisCallback; |
| 10 | +import org.springframework.data.redis.core.StringRedisTemplate; |
| 11 | +import org.springframework.data.redis.core.script.DefaultRedisScript; |
| 12 | +import org.springframework.data.redis.core.script.RedisScript; |
| 13 | +import org.springframework.data.redis.core.types.Expiration; |
| 14 | + |
| 15 | +import java.nio.charset.StandardCharsets; |
| 16 | +import java.util.Arrays; |
| 17 | +import java.util.List; |
| 18 | +import java.util.UUID; |
| 19 | +import java.util.concurrent.TimeUnit; |
| 20 | +import java.util.concurrent.locks.Condition; |
| 21 | +import java.util.concurrent.locks.Lock; |
| 22 | + |
| 23 | +/** |
| 24 | + * 实现简单的redis分布式锁, 支持重入, 不是红锁 |
| 25 | + * |
| 26 | + * @see <a href="https://redis.io/topics/distlock">reids distlock</a> |
| 27 | + */ |
| 28 | +public class RedisTemplateSimpleDistributedLock implements Lock { |
| 29 | + |
| 30 | + @Getter |
| 31 | + private final StringRedisTemplate redisTemplate; |
| 32 | + @Getter |
| 33 | + private final String key; |
| 34 | + @Getter |
| 35 | + private final int leaseMilliseconds; |
| 36 | + |
| 37 | + private final ThreadLocal<String> valueThreadLocal = new ThreadLocal<>(); |
| 38 | + |
| 39 | + public RedisTemplateSimpleDistributedLock(@NonNull StringRedisTemplate redisTemplate, int leaseMilliseconds) { |
| 40 | + this(redisTemplate, "lock:" + UUID.randomUUID().toString(), leaseMilliseconds); |
| 41 | + } |
| 42 | + |
| 43 | + public RedisTemplateSimpleDistributedLock(@NonNull StringRedisTemplate redisTemplate, @NonNull String key, int leaseMilliseconds) { |
| 44 | + if (leaseMilliseconds <= 0) { |
| 45 | + throw new IllegalArgumentException("Parameter 'leaseMilliseconds' must grate then 0: " + leaseMilliseconds); |
| 46 | + } |
| 47 | + this.redisTemplate = redisTemplate; |
| 48 | + this.key = key; |
| 49 | + this.leaseMilliseconds = leaseMilliseconds; |
| 50 | + } |
| 51 | + |
| 52 | + @Override |
| 53 | + public void lock() { |
| 54 | + while (!tryLock()) { |
| 55 | + try { |
| 56 | + Thread.sleep(1000); |
| 57 | + } catch (InterruptedException e) { |
| 58 | + // Ignore |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public void lockInterruptibly() throws InterruptedException { |
| 65 | + while (!tryLock()) { |
| 66 | + Thread.sleep(1000); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + @Override |
| 71 | + public boolean tryLock() { |
| 72 | + String value = valueThreadLocal.get(); |
| 73 | + if (value == null || value.length() == 0) { |
| 74 | + value = UUID.randomUUID().toString(); |
| 75 | + valueThreadLocal.set(value); |
| 76 | + } |
| 77 | + final byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); |
| 78 | + final byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8); |
| 79 | + List<Object> redisResults = redisTemplate.executePipelined(new RedisCallback<String>() { |
| 80 | + @Override |
| 81 | + public String doInRedis(RedisConnection connection) throws DataAccessException { |
| 82 | + connection.set(keyBytes, valueBytes, Expiration.milliseconds(leaseMilliseconds), RedisStringCommands.SetOption.SET_IF_ABSENT); |
| 83 | + connection.get(keyBytes); |
| 84 | + return null; |
| 85 | + } |
| 86 | + }); |
| 87 | + Object currentLockSecret = redisResults.size() > 1 ? redisResults.get(1) : redisResults.get(0); |
| 88 | + return currentLockSecret != null && currentLockSecret.toString().equals(value); |
| 89 | + } |
| 90 | + |
| 91 | + @Override |
| 92 | + public boolean tryLock(long time, @NotNull TimeUnit unit) throws InterruptedException { |
| 93 | + long waitMs = unit.toMillis(time); |
| 94 | + boolean locked = tryLock(); |
| 95 | + while (!locked && waitMs > 0) { |
| 96 | + long sleep = waitMs < 1000 ? waitMs : 1000; |
| 97 | + Thread.sleep(sleep); |
| 98 | + waitMs -= sleep; |
| 99 | + locked = tryLock(); |
| 100 | + } |
| 101 | + return locked; |
| 102 | + } |
| 103 | + |
| 104 | + @Override |
| 105 | + public void unlock() { |
| 106 | + if (valueThreadLocal.get() != null) { |
| 107 | + // 提示: 必须指定returnType, 类型: 此处必须为Long, 不能是Integer |
| 108 | + RedisScript<Long> script = new DefaultRedisScript("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end", Long.class); |
| 109 | + redisTemplate.execute(script, Arrays.asList(key), valueThreadLocal.get()); |
| 110 | + valueThreadLocal.remove(); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + @Override |
| 115 | + public Condition newCondition() { |
| 116 | + throw new UnsupportedOperationException(); |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * 获取当前锁的值 |
| 121 | + * return 返回null意味着没有加锁, 但是返回非null值并不以为着当前加锁成功(redis中key可能自动过期) |
| 122 | + */ |
| 123 | + public String getLockSecretValue() { |
| 124 | + return valueThreadLocal.get(); |
| 125 | + } |
| 126 | +} |
0 commit comments