redis分布式锁

//获取线程前缀,同时也是线程表示。通过UUID唯一性
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";

    //与线程id组合
    public boolean tryLock(String key, long timeOut) {
        //获取线程id
        String id = ID_PREFIX + Thread.currentThread().getId();
        //获取锁
        Boolean absent = redisTemplate.opsForValue().setIfAbsent(key, id, timeOut, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(absent);
    }

    public void unLock(Object key) {
        //获取存储的线程标识
        String value = redisTemplate.opsForValue().get(key).toString();
        //当前线程的线程标识
        String id = ID_PREFIX + Thread.currentThread().getId();
        //线程标识相同则删除否,则不删除
        if (id.equals(value)) {
            redisTemplate.delete(key);
        }
    }

你可能感兴趣的:(redis,分布式,java)