RedisTemplate實(shí)現(xiàn)分布式鎖

微服務(wù)的時(shí)代,如果我們有些定時(shí)任務(wù)要處理,在獲取資源的時(shí)候,我們要避免重復(fù)處理。于是分布式鎖在這時(shí)候就發(fā)揮了重要作用。
讓我們來看看如何用RedisTemplate來實(shí)現(xiàn)這個(gè)分布式的鎖。

創(chuàng)建Lock幫助類


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * Description: A Redis Lock Helper
 * User: Samuel Chan
 * Date: 2020-02-04
 * Time: 17:39
 */
@Service
public class RedisLockHelper {

    public static final String LOCK_PREFIX = "redis_lock";
    public static final int LOCK_EXPIRE = 1000; // ms

    @Autowired
    RedisTemplate redisTemplate;


    /**
     *  Acquire a lock.
     *
     * @param key
     * @return got the lock or not
     */
    public boolean lock(String key){
        String lock = LOCK_PREFIX + key;

        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {

            long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());

            if (acquire) {
                return true;
            } else {

                byte[] value = connection.get(lock.getBytes());

                if (Objects.nonNull(value) && value.length > 0) {

                    long expireTime = Long.parseLong(new String(value));

                    if (expireTime < System.currentTimeMillis()) {
                        // in case the lock is expired
                        byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
                        // avoid dead lock
                        return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
                    }
                }
            }
            return false;
        });
    }

    /**
     * Delete the lock
     *
     * @param key
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }


順便寫個(gè)單元測試來試試它


import tech.comfortheart.DemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RunWith(SpringRunner.class)
@SpringBootTest(classes={DemoApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class RedisLockHelperTests {
    @Autowired
    RedisLockHelper redisHelper;
    @Test
    public void testRedis() throws InterruptedException {
        int totalThreads = 1000;
        ExecutorService executorService = Executors.newFixedThreadPool(totalThreads);

        CountDownLatch countDownLatch = new CountDownLatch(totalThreads);
        for(int i=0; i<totalThreads; i++) {
            String threadId = String.valueOf(i);
            executorService.execute( () -> {
                try {
                    testLock("hey", threadId);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        // After all thread done, acquire again, expect to be successful.
        testLock("hey", "final success");
    }

    public void testLock(String key, String threadId) throws InterruptedException {
        boolean lock = redisHelper.lock(key);
        if (lock) {
            System.out.println("Successfully got lock - " + threadId);
            Thread.sleep(2000);
            redisHelper.delete(key);
        } else {
            System.out.println("Failed to obtain lock - " + threadId);
        }
    }
}

運(yùn)行了1000個(gè)線程,結(jié)果還不錯:

2020-02-04 17:30:21.482  INFO 81555 --- [ool-1-thread-11] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
Successfully got lock - 95
Failed to obtain lock - 102
Failed to obtain lock - 890
Failed to obtain lock - 83
Failed to obtain lock - 76
Failed to obtain lock - 327
Failed to obtain lock - 893
Failed to obtain lock - 326
Failed to obtain lock - 892
Failed to obtain lock - 78
Failed to obtain lock - 88
Failed to obtain lock - 891
Failed to obtain lock - 882
Failed to obtain lock - 79
...
Failed to obtain lock - 887
Failed to obtain lock - 889
Successfully got lock - final success
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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