Wrote a simple redis distributed lock [I]

I wrote a simple distributed lock redis

 

package redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisLock2 {

    JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
    private String key;
    private String value;
    private Long timeout = 5L;
    private Long startTime;
    
    public RedisLock2(JedisPool jedis,String key) {
        super();
        this.jedisPool = jedisPool;
        this.key = key;
        value = System.currentTimeMillis()+"";
    }
    
    public RedisLock2(JedisPool jedis,String key,Long timeout) {
        super();
        this.jedisPool = jedis;
        this.key = key;
        this.timeout = timeout;
        value = System.currentTimeMillis()+"";
    }

    public boolean lock() {
        Jedis jedis = jedisPool.getResource();
        boolean ok = jedis.set(key,value, "nx", "ex", timeout)!=null;
        jedis.close();
        if (!OK) {
             // lock failed 
            return  to false ; 
        } 
        // locked successfully 
        the startTime = System.currentTimeMillis ();
         return  to true ; 
    } 
    
    public String UNLOCK () { 
        String MSG = "" ;
         Long timeConsume = System.currentTimeMillis () - the startTime;
         IF (timeConsume> 1000 * timeout ) { 
            System.out.println ( "timeout unlock ----------- key:" + key + " , ms to:" + timeConsume);
 //             to false return; 
            MSG = "timeout occurs unlock --key:" + key + ", ms to:"+timeConsume;
             return msg; 
        } 
        // here is to avoid a timeout, the release lock out other threads of the same name
         // There is a problem, that is, the following code is not an atomic operation, there may be concurrency issues, here ignored 
        Jedis jedis = jedisPool. the getResource (); 
        String S = jedis.get (Key);
         IF (value.equals (S)) {
             // release lock 
            jedis.del (Key); 
            jedis.close (); 
//             return to true; 
            MSG = "unlock success " ;
             return msg; 
        } 
        jedis.close (); 
        System.out.println ( " any other abnormal Key unsuccessful ---------: "+ Key);
//         return to false; 
        MSG = "other abnormality unsuccessful --key:" + Key;
         return MSG; 
    } 
    
    
    public  static  void MAIN1 (String [] args) throws InterruptedException { 
        JedisPool jedisPool = new new JedisPool ( "127.0.0.1", 6379 );
         // Get the object from the connection pool jedis a 
        RedisLock2 redisLock = new new RedisLock2 (jedisPool, "lock1", 1L );
         Boolean Lock = redisLock.lock ();
         IF (Lock) { 
            System.out.println ( "Get to lock up " ); 
            Thread.sleep (2000);
        }
        System.out.println(redisLock.unlock());
    }
    
    
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);
        Jedis jedis2 = jedisPool.getResource();
        
//        DistributedLock lock = new DistributedLock(jedisPool);
        
        for (int i = 0; i < 3; i++) {
//            final int k = i;
            new Thread(new Runnable() {
                @Override
                public voidRUN () {
                     for ( int J = 0; J <10; J ++ ) {
                         int K = J;
                         // connected to a local service Redis
 //                         Jedis Jedis jedis new new = ( "localhost");
                         // create a connection pool object 
                        String = code null ;
                         the try {
                             // add the distributed lock
 //                             code = Lock.lock ( "mylock"); 
                            RedisLock2 myLock = new new RedisLock2 (jedisPool, "lock1", 10L);
                             The while ( to true ) {
                                 // continue to acquire lock 
                                Boolean Lock = myLock.lock ();
                                 IF (Lock) {
                                     // if the acquired execution
                                     // get an object from the connection pool jedis 
                                    Jedis jedis = jedisPool.getResource ( );
                                     IF (! jedis.exists ( "A" + K)) { 
                                        jedis.set ( "A" + K, Thread.currentThread () getName ()).; 
                                        jedis.expire ( "A" + K, 60);
                                        System.out.println(System.currentTimeMillis() + "--" + Thread.currentThread().getName()
                                                + "--key:" + ("a" + k) + "不存在,设置值为: " + Thread.currentThread().getName());
                                        try {
                                            // Thread.sleep((long) (Math.random()*1000));
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } The else  {
                                        System.out.println (Thread.currentThread () getName (). + "--Key:" + ( "A" + K) + "exists, is:" 
                                                + jedis.get ( "A" + K )); 
                                    } 
                                    jedis.close (); 
                                    // End perform the unlocking 
                                    myLock.unlock ();
                                     BREAK ; // out of the loop 
                                } 
                                
                            } 
                            
                        } the finally {
                             // release distributed lock
 @                             lock.unlock ( "mylock", code); 
                        } 
                    } 
                } 
            .}) Start (); 
        } 
    } 
    
    
}

 

Guess you like

Origin www.cnblogs.com/libin6505/p/11284401.html
Recommended