基於Redis實現---分布式鎖與實現

來源:互聯網
上載者:User
概述

目前幾乎很多大型網站及應用都是分布式部署的,分布式情境中的資料一致性問題一直是一個比較重要的話題。分布式的CAP理論告訴我們“任何一個分布式系統都無法同時滿足一致性(Consistency)、可用性(Availability)和分區容錯性(Partition tolerance),最多隻能同時滿足兩項。”所以,很多系統在設計之初就要對這三者做出取捨。在互連網領域的絕大多數的情境中,都需要犧牲強一致性來換取系統的高可用性,系統往往只需要保證“最終一致性”,只要這個最終時間是在使用者可以接受的範圍內即可。

在很多情境中,我們為了保證資料的最終一致性,需要很多的技術方案來支援,比如分散式交易、分布式鎖等。 選用Redis實現分布式鎖原因 Redis有很高的效能 Redis命令對此支援較好,實現起來比較方便 使用命令介紹

SETNX

SETNX key val
若且唯若key不存在時,set一個key為val的字串,返回1;若key存在,則什麼都不做,返回0。

expire

expire key timeout
為key設定一個逾時時間,單位為second,超過這個時間鎖會自動釋放,避免死結。

delete

delete key
刪除key

在使用Redis實現分布式鎖的時候,主要就會使用到這三個命令。 實現

使用的是jedis來串連Redis。

實現思想 擷取鎖的時候,使用setnx加鎖,並使用expire命令為鎖添加一個逾時時間,超過該時間則自動釋放鎖,鎖的value值為一個隨機產生的UUID,通過此在釋放鎖的時候進行判斷。 擷取鎖的時候還設定一個擷取的逾時時間,若超過這個時間則放棄擷取鎖。 釋放鎖的時候,通過UUID判斷是不是該鎖,若是該鎖,則執行delete進行鎖釋放。

分布式鎖的核心代碼如下:

import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.Transaction;import redis.clients.jedis.exceptions.JedisException;import java.util.List;import java.util.UUID;public class DistributedLock {    private final JedisPool jedisPool;    public DistributedLock(JedisPool jedisPool) {        this.jedisPool = jedisPool;    }    /**     * 加鎖     * @param locaName  鎖的key     * @param acquireTimeout  擷取逾時時間     * @param timeout   鎖的逾時時間     * @return 鎖標識     */    public String lockWithTimeout(String locaName,                                  long acquireTimeout, long timeout) {        Jedis conn = null;        String retIdentifier = null;        try {            // 擷取串連            conn = jedisPool.getResource();            // 隨機產生一個value            String identifier = UUID.randomUUID().toString();            // 鎖名,即key值            String lockKey = "lock:" + locaName;            // 逾時時間,上鎖後超過此時間則自動釋放鎖            int lockExpire = (int)(timeout / 1000);            // 擷取鎖的逾時時間,超過這個時間則放棄擷取鎖            long end = System.currentTimeMillis() + acquireTimeout;            while (System.currentTimeMillis() < end) {                if (conn.setnx(lockKey, identifier) == 1) {                    conn.expire(lockKey, lockExpire);                    // 返回value值,用於釋放鎖時間確認                    retIdentifier = identifier;                    return retIdentifier;                }                // 返回-1代表key沒有設定逾時時間,為key設定一個逾時時間                if (conn.ttl(lockKey) == -1) {                    conn.expire(lockKey, lockExpire);                }                try {                    Thread.sleep(10);                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                }            }        } catch (JedisException e) {            e.printStackTrace();        } finally {            if (conn != null) {                conn.close();            }        }        return retIdentifier;    }    /**     * 釋放鎖     * @param lockName 鎖的key     * @param identifier    釋放鎖的標識     * @return     */    public boolean releaseLock(String lockName, String identifier) {        Jedis conn = null;        String lockKey = "lock:" + lockName;        boolean retFlag = false;        try {            conn = jedisPool.getResource();            while (true) {                // 監視lock,準備開始事務                conn.watch(lockKey);                // 通過前面返回的value值判斷是不是該鎖,若是該鎖,則刪除,釋放鎖                if (identifier.equals(conn.get(lockKey))) {                    Transaction transaction = conn.multi();                    transaction.del(lockKey);                    List<Object> results = transaction.exec();                    if (results == null) {                        continue;                    }                    retFlag = true;                }                conn.unwatch();                break;            }        } catch (JedisException e) {            e.printStackTrace();        } finally {            if (conn != null) {                conn.close();            }        }        return retFlag;    }}

測試

下面就用一個簡單的例子測試剛才實現的分布式鎖。
例子中使用50個線程類比秒殺一個商品,使用--運算子來實現商品減少,從結果有序性就可以看出是否為加鎖狀態。

類比秒殺服務,在其中配置了jedis線程池,在初始化的時候傳給分布式鎖,供其使用。

import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class Service {    private static JedisPool pool = null;    static {        JedisPoolConfig config = new JedisPoolConfig();        // 設定最大串連數        config.setMaxTotal(200);        // 設定最大空閑數        config.setMaxIdle(8);        // 設定最大等待時間        config.setMaxWaitMillis(1000 * 100);        // 在borrow一個jedis執行個體時,是否需要驗證,若為true,則所有jedis執行個體均是可用的        config.setTestOnBorrow(true);        pool = new JedisPool(config, "127.0.0.1", 6379, 3000);    }    DistributedLock lock = new DistributedLock(pool);    int n = 500;    public void seckill() {        // 返回鎖的value值,供釋放鎖時候進行判斷        String indentifier = lock.lockWithTimeout("resource", 5000, 1000);        System.out.println(Thread.currentThread().getName() + "獲得了鎖");        System.out.println(--n);        lock.releaseLock("resource", indentifier);    }}

// 類比線程進行秒殺服務

public class ThreadA extends Thread {    private Service service;    public ThreadA(Service service) {        this.service = service;    }    @Override    public void run() {        service.seckill();    }}public class Test {    public static void main(String[] args) {        Service service = new Service();        for (int i = 0; i < 50; i++) {            ThreadA threadA = new ThreadA(service);            threadA.start();        }    }}

結果如下,結果為有序的。

若注釋掉使用鎖的部分

public void seckill() {    // 返回鎖的value值,供釋放鎖時候進行判斷    //String indentifier = lock.lockWithTimeout("resource", 5000, 1000);    System.out.println(Thread.currentThread().getName() + "獲得了鎖");    System.out.println(--n);    //lock.releaseLock("resource", indentifier);}

從結果可以看出,有一些是非同步進行的。

在分布式環境中,對資源進行上鎖有時候是很重要的,比如搶購某一資源,這時候使用分布式鎖就可以很好地控制資源。
當然,在具體使用中,還需要考慮很多因素,比如逾時時間的選取,擷取鎖時間的選取對並發量都有很大的影響,上述實現的分布式鎖也只是一種簡單的實現,主要是一種思想。

使用zookeeper實現分布式鎖,使用zookeeper的可靠性是要大於使用redis實現的分布式鎖的,但是相比而言,redis的效能更好。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.