Distributed lock implementation (1)

Distributed locks are implemented using Redis's SETNX command.

Introduction to the SETNX command

command format

SETNX key value

Set the value of key to value if and only if key does not exist. 
If the given key already exists, SETNX does nothing. 
SETNX is shorthand for SET if Not eXists.

return value

Returns an integer, specifically 
- 1, when the value of key is set 
- 0, when the value of key is not set

example

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

Java code implementation

	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("Timeout to acquire lock:"+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();
			}
		}
    }

2. Another distributed lock implementation ( redssion ) based on Redis: http://blog.csdn.net/wwd0501/article/details/50717111

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325988132&siteId=291194637