redisロックRedlock

3565 ワード

参考記事:https://blog.csdn.net/pfnie/article/details/52234735#commentBox

public class RedisUtil {

    //    
    public static int ONE_DAY = 60 * 60 * 24;


    //      , 
    private static long LOCK_EXPIRE = 60L;

    //        
    private static long LOCK_TIME_OUT = 10L * 1000000000L;

    //   
    private static String LOCK_KEY = "lock";

    //   
    private static String LOCK_VALUE = "1";

    public void lock(StringRedisTemplate template) {
        //       
        long nowTime = System.nanoTime();
        //        
        Random r = new Random();
        RedisConnection connection = template.getConnectionFactory().getConnection();
        try {
            long l = System.nanoTime() - nowTime;
            while (l < LOCK_TIME_OUT) {
                //      
                if (connection.setNX(LOCK_KEY.getBytes(), LOCK_VALUE.getBytes())) {
                    //    ,       ,      ,      
                    template.expire(LOCK_KEY, LOCK_EXPIRE, TimeUnit.SECONDS);
                    break;
                } else {
                    //   ,   。         ,                    
                    Thread.sleep(5, r.nextInt(100));
                    l = System.nanoTime() - nowTime;
                }
            }
            if (l > LOCK_TIME_OUT) {
                System.out.println("  ");
                System.out.println("    :" + l);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connection.close();
        }
    }

    public void unLock(StringRedisTemplate template) {
        template.delete(LOCK_KEY);
    }
}