zoukankan      html  css  js  c++  java
  • zookeeper分布式锁用法

    package com.example.demo3.zk;
    
    import lombok.extern.slf4j.Slf4j;
    import org.apache.storm.shade.org.apache.zookeeper.*;
    import java.util.concurrent.CountDownLatch;
    
    /**
     * Zookeeper 初始化,获取锁,释放锁。创建临时锁。
     */
    @Slf4j
    public class ZooKeeperSession {
    
        private static CountDownLatch countDownLatch=new CountDownLatch(1);
    
        private ZooKeeper zooKeeper;
    
        //目录
        private String lockPath="/orderId-lock-";
    
        /**
         * 连接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;
            }
        }
    
        /**
         * 获取单例。
         * @return
         */
        public static ZooKeeperSession getInstance(){
            return Singleton.getIntance();
        }
    
        /**
         * 初始化单例方法。
         */
        public static void init(){
            getInstance();
        }
    }

    调用方法:

    package com.example.demo3;
    
    import com.example.demo3.zk.ZooKeeperSession;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.Test;
    
    @Slf4j
    public class TestZooKeeper extends Demo3ApplicationTests {
    
        /**
         * 测试分布式锁。
         */
        @Test
        public void testZookeeper() {
            Long orderId = 1L;
            ZooKeeperSession zooKeeperSession = new ZooKeeperSession();
            log.info("获取锁");
            zooKeeperSession.acquireDistributeLock(orderId);
            log.info("执行业务逻辑...");
            zooKeeperSession.releaseDistributeLock(orderId);
            log.info("释放锁");
        }
    
    }

    运行结果:

    源码下载地址:

    链接:https://pan.baidu.com/s/1rgyoxf9lLTjDIWX-Ro5o-Q
    提取码:ke31

  • 相关阅读:
    维护是关键 刻录机不读/刻盘故障实例排除
    压缩viewstate
    采用"软改"的方式激活Windows 7
    开启VAIO的VT
    比较通用的存储过程分页
    linux如何安装声卡驱动
    给Fedora11安装五笔
    导入CSV文件到数据库
    Ubuntu第一次登录用户名和密码错误不能登录
    CSS中Position、absolute、Relative、fixed、static的用法
  • 原文地址:https://www.cnblogs.com/xiaozw/p/11926816.html
Copyright © 2011-2022 走看看