基于redis的分布式并發(fā)鎖java實(shí)現(xiàn)

基于redis分布式并發(fā)鎖的實(shí)現(xiàn)理論原理:
https://github.com/huangz1990/redis/commit/18dbaee4f40f435970a09da427b8f45bd26b4072#diff-b643df753e12d0d07a872f91487c957dR34

主要概念:
1、如何爭(zhēng)鎖
2、鎖的表達(dá)方式
3、避免死鎖
4、死鎖過(guò)期

網(wǎng)上找了一些資料:針對(duì)redisTemplate 實(shí)現(xiàn)的,但是在試用過(guò)的過(guò)程中也遇到了一些坑:

public interface DistributionLock {
    //加鎖成功 返回加鎖時(shí)間
     Long lock(String lockKey, String threadname);

    //解鎖 需要更加加鎖時(shí)間判斷是否有權(quán)限
     void unlock(String lockKey, Long lockvalue, String threadname);
}
public class RedisDistributionLock implements DistributionLock{

    private static final long LOCK_TIMEOUT = 10 * 1000; //加鎖超時(shí)時(shí)間 單位毫秒  意味著加鎖期間內(nèi)執(zhí)行完操作 如果未完成會(huì)有并發(fā)現(xiàn)象
    private static final Logger LOG = LoggerFactory.getLogger(RedisDistributionLock.class); //redis鎖日志

    @Autowired
    @Qualifier("redisTemplateSerializable")
    private  RedisTemplate<Serializable, Serializable> redisTemplate;
  //如果遇到多個(gè)RedisTemplate可以根據(jù)名字進(jìn)行注入
    @Resource(name = "redisTemplateString")
    private RedisTemplate<String, String> redisTemplateString;
    /**
     * 取到鎖加鎖 取不到鎖一直等待直到獲得鎖
     */
    @Override
    public synchronized Long lock(final String lockKey, String threadname) {
        LOG.info(threadname + "開(kāi)始執(zhí)行加鎖");
        while (true) { //循環(huán)獲取鎖
            final Long lock_timeout = System.currentTimeMillis() + LOCK_TIMEOUT + 1; //鎖時(shí)間
            if (redisTemplate.execute(new RedisCallback<Boolean>() {
                @Override
                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();
                    byte[] value = jdkSerializer.serialize(lock_timeout);
                    return connection.setNX(lockKey.getBytes(), value);
                }
            })) { //如果加鎖成功
                LOG.info(threadname + "---加鎖成功---lockKey:{},lock_timeout:{}",lockKey,lock_timeout);
                redisTemplate.expire(lockKey, LOCK_TIMEOUT, TimeUnit.MILLISECONDS); //設(shè)置超時(shí)時(shí)間,釋放內(nèi)存
                return lock_timeout;
            }else {
                Long currt_lock_timeout_Str =
                        (Long) redisTemplate.opsForValue().get(lockKey); // redis里的時(shí)間
                if (currt_lock_timeout_Str != null && currt_lock_timeout_Str < System.currentTimeMillis()) { //鎖已經(jīng)失效
                    // 判斷是否為空,不為空的情況下,說(shuō)明已經(jīng)失效,如果被其他線程設(shè)置了值,則第二個(gè)條件判斷是無(wú)法執(zhí)行
                    Long old_lock_timeout_Str = (Long) redisTemplate.opsForValue().getAndSet(lockKey, lock_timeout);
                    // 獲取上一個(gè)鎖到期時(shí)間,并設(shè)置現(xiàn)在的鎖到期時(shí)間
                    if (old_lock_timeout_Str != null && old_lock_timeout_Str.equals(currt_lock_timeout_Str)) {
                        // 如過(guò)這個(gè)時(shí)候,多個(gè)線程恰好都到了這里,但是只有一個(gè)線程的設(shè)置值和當(dāng)前值相同,他才有權(quán)利獲取鎖
                        LOG.info(threadname + "---加鎖成功---lockKey:{},lock_timeout:{}",lockKey,lock_timeout);
                        redisTemplate.expire(lockKey, LOCK_TIMEOUT, TimeUnit.MILLISECONDS); //設(shè)置超時(shí)時(shí)間,釋放內(nèi)存
                        return lock_timeout;//返回加鎖時(shí)間
                    }
                }
            }
            try {
                LOG.info(threadname +  "等待加鎖,睡眠100毫秒");
                TimeUnit.MILLISECONDS.sleep(100);//睡眠100毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public synchronized void unlock(String lockKey, Long lockvalue, String threadname) {
        Long currt_lock_timeout_Str = (Long) redisTemplate.opsForValue().get(lockKey); // redis里的時(shí)間
        if (currt_lock_timeout_Str != null && currt_lock_timeout_Str .equals( lockvalue)) {//如果是加鎖者 則刪除鎖 如果不是則等待自動(dòng)過(guò)期 重新競(jìng)爭(zhēng)加鎖
            redisTemplate.delete(lockKey); //刪除鍵
            LOG.info(threadname + "解鎖成功:lockKey{},lockValue:{}",lockKey,lockvalue);
        }
    }

}

關(guān)鍵點(diǎn):這里的集中序列化方式一定要配置,不然取不到值,調(diào)試了很久

@Bean("redisTemplateSerializable")
    RedisTemplate<Serializable,Serializable> redisTemplateSerializable(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Serializable, Serializable> template = new RedisTemplate<Serializable, Serializable>();
        template.setConnectionFactory(connectionFactory);
        /**
         * 添加屬性
         */
        StringRedisSerializer stringRedisSerializernew =new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializernew);
        template.setHashKeySerializer(stringRedisSerializernew);
        JdkSerializationRedisSerializer jdkSerializationRedisSerializer =new JdkSerializationRedisSerializer();
        template.setValueSerializer(jdkSerializationRedisSerializer);
        template.setHashValueSerializer(jdkSerializationRedisSerializer);
        return template;
    }

測(cè)試代碼:要注意的是:最好在外層加同步鎖,否則會(huì)出現(xiàn)一種奇怪的現(xiàn)象,就是每次都是到鎖過(guò)期才釋放鎖,搶先進(jìn)入任務(wù)的線程,會(huì)被堵在釋放鎖的外面:

@RequestMapping(value = {"/redis/dist/test/{lockKey}"},method = RequestMethod.GET)
    public void testDistLock(@PathVariable("lockKey") String lockKey1){
        AtomicBoolean isFinish = new AtomicBoolean(false);
        final ReentrantLock lock = new ReentrantLock();
        for(int i=0;i<1;i++){
            final String lockKey = lockKey1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        lock.lockInterruptibly();
                        Long lockValue = redisDistributionLock.lock(lockKey,Thread.currentThread().getName());
                        System.out.println("獲得鎖:"+lockValue);
                        System.out.println("執(zhí)行任務(wù)......");
//                        redisDistributionLock.unlock(lockKey,lockValue,Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }

                }
            }).start();
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容