美文网首页
Springboot Redis 分布式锁

Springboot Redis 分布式锁

作者: Java程序员 | 来源:发表于2018-08-08 15:18 被阅读0次
  • 首先搭建springboot1.X 项目

  • 倒入redis相关的JAR

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
    
  • 加锁

                    public boolean setNx(String lockKey, String requestId, int expireTime) {
                          boolean success = stringRedisTemplate.execute((RedisCallback<Boolean>) 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<Long> script = new DefaultRedisScript(scriptStr, Long.class);
                                List<String> keys = new ArrayList<>();
                                keys.add(lockKey);
                                Long result = stringRedisTemplate.execute(script, new StringRedisSerializer(), new RedisSerializer<Long>() {
                                    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 分布式锁

      本文链接:https://www.haomeiwen.com/subject/zfcxbftx.html