分布式锁实现(一)

使用Redis的 SETNX 命令实现分布式锁。

SETNX命令简介

命令格式

SETNX key value

将 key 的值设为 value,当且仅当 key 不存在。 
若给定的 key 已经存在,则 SETNX 不做任何动作。 
SETNX 是SET if Not eXists的简写。

返回值

返回整数,具体为 
- 1,当 key 的值被设置 
- 0,当 key 的值没被设置

例子

redis> SETNX mykey “hello” 
(integer) 1 
redis> SETNX mykey “hello” 
(integer) 0 
redis> GET mykey 
“hello” 

Java代码实现

	public boolean getRedisLock(String LockValue) {
    	Jedis jedis=null;
    	try {
    		jedis = os_write_pool.getResource();
	        long now = System.currentTimeMillis();
	        int timeout = 2;
	        while(true) {
	            if ((System.currentTimeMillis() - now) > timeout) {
	            	logger.error("获取锁超时:"+LockValue);
	                now = System.currentTimeMillis();
	                jedis.del(LockValue);
	                return false;
	            }            
	            if (jedis.setnx(LockValue, "Lock") == 1) {
	            	jedis.expire(LockValue, timeout);
	                break;
	            }
	            try {
					Thread.currentThread().sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
	        }
    	} catch (Exception e) {
    		logger.error("getRedisLock is error:"+LockValue);
		}finally{
			if(jedis!=null){
				jedis.close();
			}
		}
        return true;
    }
	
	 public void releaseRedisLock(String LockValue) {
    	Jedis jedis=null;
    	try {
    		jedis=os_write_pool.getResource();
    		jedis.del(LockValue);
    	} catch (Exception e) {
    		logger.error("getRedisLock is error:"+LockValue);
		}finally{
			if(jedis!=null){
				jedis.close();
			}
		}
    }

二、基于Redis实现的另一种分布式锁实现(redssion)地址:http://blog.csdn.net/wwd0501/article/details/50717111

猜你喜欢

转载自blog.csdn.net/wwd0501/article/details/79472511