Springboot Redis 分布式锁

2018-08-08  本文已影响0人  Java程序员
                            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;
                            }
上一篇 下一篇

猜你喜欢

热点阅读