zookeeper distributed lock usage

Package com.example.demo3.zk; 

Import lombok.extern.slf4j.Slf4j;
 Import org.apache.storm.shade.org.apache.zookeeper *. ;
 Import java.util.concurrent.CountDownLatch; 

/ ** 
 * initialize the Zookeeper acquiring a lock, release the lock. Create a temporary lock. 
 * / 
@ SLF4J 
public  class ZooKeeperSession { 

    Private  static a CountDownLatch CountDownLatch = new new a CountDownLatch (. 1 ); 

    Private the ZooKeeper ZooKeeper; 

    // directory 
    Private String lockPath = "/ the orderId-lock -" ; 

    / ** 
     * connected ZooKeeper 
     * / 
    public ZooKeeperSession(){
        try {
            //连接zk服务器
            this.zooKeeper=new ZooKeeper("192.168.132.154:2181,192.168.132.156:2181,192.168.132.155:2181",
                    50000,new ZooKeeperWatcher());
            log.info("状态:"+zooKeeper.getState().toString());

            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("ZooKeeper session 建立......");
    }

    /**
     * 获取分布式锁。
     * @param orderId
     */
    public void acquireDistributeLock(Long orderId) {
        String path = lockPath + orderId;
        try {
            zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            log.info("success to acquire lock for order[id=" + orderId + "]");
        } catch (Exception e) {
            e.printStackTrace();
            int count = 0;
            while (true) {
                try {
                    Thread.sleep(20);
                    zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

                } catch (Exception e1) {
                    e1.printStackTrace();
                    count++;
                    continue;
                }
                log.info("success to acquire lock for order[id=" + orderId + " after " + count + " times try......");
                break;
            }
        }
    }

    /**
     * 释放分布式锁。
     * @param orderId
     */
    public void releaseDistributeLock(Long orderId){
        String path = lockPath+orderId;
        try {
            zooKeeper.delete(path,-1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }

    private class ZooKeeperWatcher implements Watcher{

        @Override
        public void process(WatchedEvent event) {
            log.info("Receive watch event:"+event.getState());
            if(Event.KeeperState.SyncConnected == event.getState()){
                countDownLatch.countDown();
            }
        }
    }

    /**
     * 封装单例静态内部类。
     */
    private static class Singleton{
        private static ZooKeeperSession instance;

        static {
            instance=new ZooKeeperSession();
        } 

        Public  static ZooKeeperSession getIntance () {
             return instance; 
        } 
    } 

    / ** 
     * Gets the singleton. 
     * @Return 
     * / 
    public  static ZooKeeperSession the getInstance () {
         return ; () Singleton.getIntance 
    } 

    / ** 
     * Example are initialized. 
     * / 
    Public  static  void the init () { 
        the getInstance (); 
    } 
}

 

Call the method:

Package com.example.demo3; 

Import com.example.demo3.zk.ZooKeeperSession;
 Import lombok.extern.slf4j.Slf4j;
 Import org.junit.Test; 

@ SLF4J 
public  class TestZooKeeper the extends Demo3ApplicationTests { 

    / ** 
     * Testing Distributed Lock . 
     * / 
    @Test 
    public  void testZookeeper () { 
        Long the orderId = 1L ; 
        ZooKeeperSession zooKeeperSession = new new ZooKeeperSession (); 
        log.info ( "lock acquisition" );
        zooKeeperSession.acquireDistributeLock(orderId);
        log.info ( ); "execute business logic ..." 
        zooKeeperSession.releaseDistributeLock (the orderId); 
        log.info ( "lock release" ); 
    } 

}

 

operation result:

 

Source Download:

Link: https: //pan.baidu.com/s/1rgyoxf9lLTjDIWX-Ro5o-Q
extraction code: ke31

 

Guess you like

Origin www.cnblogs.com/xiaozw/p/11926816.html