Springboot Redis 分布式锁

  • 首先搭建springboot1.X 项目

  • 倒入redis相关的JAR

      
          org.springframework.boot
          spring-boot-starter-data-redis
      
    
  • 加锁

                    public boolean setNx(String lockKey, String requestId, int expireTime) {
                          boolean success = stringRedisTemplate.execute((RedisCallback) connection -> 
                          connection.set(lockKey.getBytes(), requestId.getBytes(), Expiration.from(expireTime, TimeUnit.SECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT));
                          return success;
                   }
    
  • 释放锁

                            public boolean releaseDistributedLock(String lockKey, String requestId) {
                                String scriptStr = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                                DefaultRedisScript script = new DefaultRedisScript(scriptStr, Long.class);
                                List keys = new ArrayList<>();
                                keys.add(lockKey);
                                Long result = stringRedisTemplate.execute(script, new StringRedisSerializer(), new RedisSerializer() {
                                    private final Charset charset = Charset.forName("UTF8");
                        
                                    @Override
                                    public byte[] serialize(Long aLong) throws SerializationException {
                                        return (aLong == null ? null : (aLong.toString()).getBytes(charset));
                                    }
                        
                                    @Override
                                    public Long deserialize(byte[] bytes) throws SerializationException {
                                        return (bytes == null ? null : Long.parseLong(new String(bytes, charset)));
                                    }
                                }, keys, requestId);
                                if (RELEASE_SUCCESS.equals(result)) {
                                    return true;
                                }
                                return false;
                            }

你可能感兴趣的:(Springboot Redis 分布式锁)