主頁 > 知識庫 > redis鎖機制介紹與實例

redis鎖機制介紹與實例

熱門標簽:網站排名優(yōu)化 AI電銷 百度競價排名 Linux服務器 呼叫中心市場需求 服務外包 鐵路電話系統(tǒng) 地方門戶網站

1 悲觀鎖

執(zhí)行操作前假設當前的操作肯定(或有很大幾率)會被打斷(悲觀)?;谶@個假設,我們在做操作前就會把相關資源鎖定,不允許自己執(zhí)行期間有其他操作干擾。

Redis不支持悲觀鎖。Redis作為緩存服務器使用時,以讀操作為主,很少寫操作,相應的操作被打斷的幾率較少。不采用悲觀鎖是為了防止降低性能。

2 樂觀鎖

執(zhí)行操作前假設當前操作不會被打斷(樂觀)?;谶@個假設,我們在做操作前不會鎖定資源,萬一發(fā)生了其他操作的干擾,那么本次操作將被放棄。

3. Redis中的鎖策略

Redis采用了樂觀鎖策略(通過watch操作)。樂觀鎖支持讀操作,適用于多讀少寫的情況!
在事務中,可以通過watch命令來加鎖;使用 UNWATCH可以取消加鎖;
如果在事務之前,執(zhí)行了WATCH(加鎖),那么執(zhí)行EXEC 命令或 DISCARD 命令后,鎖對自動釋放,即不需要再執(zhí)行 UNWATCH 了

例子

redis鎖工具類

package com.fly.lock;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisLock {
  //初始化redis池
  private static JedisPoolConfig config;
  private static JedisPool pool;
  static {
    config = new JedisPoolConfig();
    config.setMaxTotal(30);
    config.setMaxIdle(10);
    pool = new JedisPool(config, "192.168.233.200", 6379);
  }
  /**
   * 給target上鎖
   * @param target
   **/
  public static void lock(Object target) {
    //獲取jedis
    Jedis jedis = pool.getResource();
    //result接收setnx的返回值,初始值為0
    Long result= 0L;
    while (result  1) {
      //如果target在redis中已經存在,則返回0;否則,在redis中設置target鍵值對,并返回1
      result = jedis.setnx(target.getClass().getName() + target.hashCode(), Thread.currentThread().getName());
    }
    jedis.close();
  }
  /**
   * 給target解鎖
   * @param target
   **/
  public static void unLock(Object target) {
    Jedis jedis = pool.getResource();
    //刪除redis中target對象的鍵值對
    Long del = jedis.del(target.getClass().getName() + target.hashCode());
    jedis.close();
  }
  /**
   * 嘗試給target上鎖,如果鎖成功返回true,如果鎖失敗返回false
   * @param target
   * @return
   **/
  public static boolean tryLock(Object target) {
    Jedis jedis = pool.getResource();
    Long row = jedis.setnx(target.getClass().getName() + target.hashCode(), "true");
    jedis.close();
    if (row > 0) {
      return true;
    }
    return false;
  }
}

測試類

package com.fly.test;
import com.fly.lock.RedisLock;
class Task {
  public void doTask() {
    //上鎖
    RedisLock.lock(this);
    System.out.println("當前線程: " + Thread.currentThread().getName());
    System.out.println("開始執(zhí)行: " + this.hashCode());
    try {
      System.out.println("doing...");
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("完成: " + this.hashCode());
    //解鎖
    RedisLock.unLock(this);
  }
}
public class Demo {
  public static void main(String[] args) {
    Task task = new Task();
    Thread[] threads = new Thread[5];
    for (Thread thread : threads) {
      thread = new Thread(()->{
        task.doTask();
      });
      thread.start();
    }
  }
}

輸出結果:

----------------------------------------------
當前線程: Thread-0
開始執(zhí)行: 2081499965
doing...
完成: 2081499965
----------------------------------------------
當前線程: Thread-2
開始執(zhí)行: 2081499965
doing...
完成: 2081499965
----------------------------------------------
當前線程: Thread-1
開始執(zhí)行: 2081499965
doing...
完成: 2081499965
----------------------------------------------
當前線程: Thread-4
開始執(zhí)行: 2081499965
doing...
完成: 2081499965
----------------------------------------------
當前線程: Thread-3
開始執(zhí)行: 2081499965
doing...
完成: 2081499965

去掉redis鎖后,執(zhí)行結果:

----------------------------------------------
----------------------------------------------
當前線程: Thread-2
開始執(zhí)行: 1926683415
----------------------------------------------
當前線程: Thread-1
doing...
當前線程: Thread-0
----------------------------------------------
當前線程: Thread-3
開始執(zhí)行: 1926683415
doing...
開始執(zhí)行: 1926683415
doing...
----------------------------------------------
開始執(zhí)行: 1926683415
doing...
當前線程: Thread-4
開始執(zhí)行: 1926683415
doing...
完成: 1926683415
完成: 1926683415
完成: 1926683415
完成: 1926683415
完成: 1926683415

Process finished with exit code 0

利用redis這個性質,可以實現分布式鎖,當然設計一定復雜一些!

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接

您可能感興趣的文章:
  • CentoS6.5環(huán)境下redis4.0.1(stable)安裝和主從復制配置方法
  • Redis教程(九):主從復制配置實例
  • Redis主從復制問題和擴容問題的解決思路
  • gem install redis報錯的解決方案
  • 使用Ruby腳本部署Redis Cluster集群步驟講解
  • Redis Cluster的圖文講解
  • Redis cluster集群的介紹
  • redis持久化的介紹
  • SpringBoot AOP控制Redis自動緩存和更新的示例
  • Redis主從復制詳解

標簽:黃山 銅川 衡水 崇左 仙桃 湘潭 蘭州 湖南

巨人網絡通訊聲明:本文標題《redis鎖機制介紹與實例》,本文關鍵詞  ;如發(fā)現本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266