redis分布式锁的作用及实现

一、什么是分布式锁?

要介绍分布式锁,首先要提到与分布式锁相对应的是线程锁、进程锁。

线程锁:主要用来给方法、代码块加锁。当某个方法或代码使用锁,在同一时刻仅有一个线程执行该方法或该代码段。线程锁只在同一JVM中有效果,因为线程锁的实现在根本上是依靠线程之间共享内存实现的,比如synchronized是共享对象头,显示锁Lock是共享某个变量(state)。

进程锁:为了控制同一操作系统中多个进程访问某个共享资源,因为进程具有独立性,各个进程无法访问其他进程的资源,因此无法通过synchronized等线程锁实现进程锁。

分布式锁:当多个进程不在同一个系统中,用分布式锁控制多个进程对资源的访问。

二、分布式锁的使用场景。

线程间并发问题和进程间并发问题都是可以通过分布式锁解决的,但是强烈不建议这样做!因为采用分布式锁解决这些小问题是非常消耗资源的!分布式锁应该用来解决分布式情况下的多进程并发问题才是最合适的。

有这样一个情境,线程A和线程B都共享某个变量X。

如果是单机情况下(单JVM),线程之间共享内存,只要使用线程锁就可以解决并发问题。

如果是分布式情况下(多JVM),线程A和线程B很可能不是在同一JVM中,这样线程锁就无法起到作用了,这时候就要用到分布式锁来解决。

三、分布式锁的实现(Redis)

分布式锁实现的关键是在分布式的应用服务器外,搭建一个存储服务器,存储锁信息,这时候我们很容易就想到了Redis。首先我们要搭建一个Redis服务器,用Redis服务器来存储锁信息。

在实现的时候要注意的几个关键点:

1、锁信息必须是会过期超时的,不能让一个线程长期占有一个锁而导致死锁;

2、同一时刻只能有一个线程获取到锁。

几个要用到的redis命令:

setnx(key, value):“set if not exits”,若该key-value不存在,则成功加入缓存并且返回1,否则返回0。

get(key):获得key对应的value值,若不存在则返回nil。

getset(key, value):先获取key对应的value值,若不存在则返回nil,然后将旧的value更新为新的value。

expire(key, seconds):设置key-value的有效期为seconds秒。

看一下流程图:


在这个流程下,不会导致死锁。

我采用Jedis作为Redis客户端的api,下面来看一下具体实现的代码。

(1)首先要创建一个Redis连接池。

[java]  view plain  copy
  1. public class RedisPool {  
  2.   
  3.     private static JedisPool pool;//jedis连接池  
  4.   
  5.     private static int maxTotal = 20;//最大连接数  
  6.   
  7.     private static int maxIdle = 10;//最大空闲连接数  
  8.   
  9.     private static int minIdle = 5;//最小空闲连接数  
  10.   
  11.     private static boolean testOnBorrow = true;//在取连接时测试连接的可用性  
  12.   
  13.     private static boolean testOnReturn = false;//再还连接时不测试连接的可用性  
  14.   
  15.     static {  
  16.         initPool();//初始化连接池  
  17.     }  
  18.   
  19.     public static Jedis getJedis(){  
  20.         return pool.getResource();  
  21.     }  
  22.   
  23.     public static void close(Jedis jedis){  
  24.         jedis.close();  
  25.     }  
  26.   
  27.     private static void initPool(){  
  28.         JedisPoolConfig config = new JedisPoolConfig();  
  29.         config.setMaxTotal(maxTotal);  
  30.         config.setMaxIdle(maxIdle);  
  31.         config.setMinIdle(minIdle);  
  32.         config.setTestOnBorrow(testOnBorrow);  
  33.         config.setTestOnReturn(testOnReturn);  
  34.         config.setBlockWhenExhausted(true);  
  35.         pool = new JedisPool(config, "127.0.0.1"63795000"liqiyao");  
  36.     }  
  37. }  

(2)对Jedis的api进行封装,封装一些实现分布式锁需要用到的操作。

[java]  view plain  copy
  1. public class RedisPoolUtil {  
  2.   
  3.     private RedisPoolUtil(){}  
  4.   
  5.     private static RedisPool redisPool;  
  6.   
  7.     public static String get(String key){  
  8.         Jedis jedis = null;  
  9.         String result = null;  
  10.         try {  
  11.             jedis = RedisPool.getJedis();  
  12.             result = jedis.get(key);  
  13.         } catch (Exception e){  
  14.             e.printStackTrace();  
  15.         } finally {  
  16.             if (jedis != null) {  
  17.                 jedis.close();  
  18.             }  
  19.             return result;  
  20.         }  
  21.     }  
  22.   
  23.     public static Long setnx(String key, String value){  
  24.         Jedis jedis = null;  
  25.         Long result = null;  
  26.         try {  
  27.             jedis = RedisPool.getJedis();  
  28.             result = jedis.setnx(key, value);  
  29.         } catch (Exception e){  
  30.             e.printStackTrace();  
  31.         } finally {  
  32.             if (jedis != null) {  
  33.                 jedis.close();  
  34.             }  
  35.             return result;  
  36.         }  
  37.     }  
  38.   
  39.     public static String getSet(String key, String value){  
  40.         Jedis jedis = null;  
  41.         String result = null;  
  42.         try {  
  43.             jedis = RedisPool.getJedis();  
  44.             result = jedis.getSet(key, value);  
  45.         } catch (Exception e){  
  46.             e.printStackTrace();  
  47.         } finally {  
  48.             if (jedis != null) {  
  49.                 jedis.close();  
  50.             }  
  51.             return result;  
  52.         }  
  53.     }  
  54.   
  55.     public static Long expire(String key, int seconds){  
  56.         Jedis jedis = null;  
  57.         Long result = null;  
  58.         try {  
  59.             jedis = RedisPool.getJedis();  
  60.             result = jedis.expire(key, seconds);  
  61.         } catch (Exception e){  
  62.             e.printStackTrace();  
  63.         } finally {  
  64.             if (jedis != null) {  
  65.                 jedis.close();  
  66.             }  
  67.             return result;  
  68.         }  
  69.     }  
  70.   
  71.     public static Long del(String key){  
  72.         Jedis jedis = null;  
  73.         Long result = null;  
  74.         try {  
  75.             jedis = RedisPool.getJedis();  
  76.             result = jedis.del(key);  
  77.         } catch (Exception e){  
  78.             e.printStackTrace();  
  79.         } finally {  
  80.             if (jedis != null) {  
  81.                 jedis.close();  
  82.             }  
  83.             return result;  
  84.         }  
  85.     }  
  86. }  

(3)分布式锁工具类

[java]  view plain  copy
  1. public class DistributedLockUtil {  
  2.   
  3.     private DistributedLockUtil(){  
  4.     }  
  5.   
  6.     public static boolean lock(String lockName){//lockName可以为共享变量名,也可以为方法名,主要是用于模拟锁信息  
  7.         System.out.println(Thread.currentThread() + "开始尝试加锁!");  
  8.         Long result = RedisPoolUtil.setnx(lockName, String.valueOf(System.currentTimeMillis() + 5000));  
  9.         if (result != null && result.intValue() == 1){  
  10.             System.out.println(Thread.currentThread() + "加锁成功!");  
  11.             RedisPoolUtil.expire(lockName, 5);  
  12.             System.out.println(Thread.currentThread() + "执行业务逻辑!");  
  13.             RedisPoolUtil.del(lockName);  
  14.             return true;  
  15.         } else {  
  16.             String lockValueA = RedisPoolUtil.get(lockName);  
  17.             if (lockValueA != null && Long.parseLong(lockValueA) >= System.currentTimeMillis()){  
  18.                 String lockValueB = RedisPoolUtil.getSet(lockName, String.valueOf(System.currentTimeMillis() + 5000));  
  19.                 if (lockValueB == null || lockValueB.equals(lockValueA)){  
  20.                     System.out.println(Thread.currentThread() + "加锁成功!");  
  21.                     RedisPoolUtil.expire(lockName, 5);  
  22.                     System.out.println(Thread.currentThread() + "执行业务逻辑!");  
  23.                     RedisPoolUtil.del(lockName);  
  24.                     return true;  
  25.                 } else {  
  26.                     return false;  
  27.                 }  
  28.             } else {  
  29.                 return false;  
  30.             }  
  31.         }  
  32.     }  
  33. }  

猜你喜欢

转载自blog.csdn.net/ntotl/article/details/80368355