1、为什么需要分布式锁
    因为在集群环境中,每个类中的全局变量在每个jvm中都保存独立的一份,互不影响,不能做到保证全局唯一。所以需要分布式锁;而zookeeper中临时节点的名称唯一性以及会话保持一致性还有节点事件通知的特性决定了zookeeper可以很好的实现分布式锁;

    2、代码实现

    1. public abstract class ZookeeperAbstractLock implements ExtLock {
    2. // 集群连接地址
    3. protected String CONNECTION = "127.0.0.1:2181";
    4. // zk客户端连接
    5. protected ZkClient zkClient = new ZkClient(CONNECTION);
    6. // path路径
    7. protected String lockPath = "/path";
    8. protected CountDownLatch countDownLatch = new CountDownLatch(1);
    9. public void getLock() {
    10. if (tryLock()) {
    11. System.out.println("####获取锁成功######");
    12. } else {
    13. waitLock();
    14. getLock();
    15. }
    16. }
    17. // 获取锁
    18. abstract boolean tryLock();
    19. // 等待锁
    20. abstract void waitLock();
    21. public void unLock() {
    22. if (zkClient != null) {
    23. System.out.println("#######释放锁#########");
    24. zkClient.close();
    25. }
    26. }
    1. public class ZookeeperDistrbuteLock extends ZookeeperAbstractLock {
    2. @Override
    3. boolean tryLock() {
    4. try {
    5. zkClient.createEphemeral(lockPath);
    6. return true;
    7. } catch (Exception e) {
    8. return false;
    9. }
    10. }
    11. @Override
    12. void waitLock() {
    13. // 使用zk临时事件监听
    14. IZkDataListener iZkDataListener = new IZkDataListener() {
    15. public void handleDataDeleted(String path) throws Exception {
    16. if (countDownLatch != null) {
    17. countDownLatch.countDown();
    18. }
    19. }
    20. public void handleDataChange(String arg0, Object arg1) throws Exception {
    21. }
    22. };
    23. // 注册事件通知
    24. zkClient.subscribeDataChanges(lockPath, iZkDataListener);
    25. if (zkClient.exists(lockPath)) {
    26. countDownLatch = new CountDownLatch(1);
    27. try {
    28. countDownLatch.await();
    29. } catch (Exception e) {
    30. // TODO: handle exception
    31. }
    32. }
    33. // 监听完毕后,移除事件通知
    34. zkClient.unsubscribeDataChanges(lockPath, iZkDataListener);
    35. }
    36. }


    public class OrderService implements Runnable {
        private OrderNumGenerator orderNumGenerator = new OrderNumGenerator();
        private ExtLock extLock = new ZookeeperDistrbuteLock();
    
        public void run() {
            getNumber();
        }
    
        public void getNumber() {
            try {
                extLock.getLock();
                String number = orderNumGenerator.getNumber();
                System.out.println("线程:" + Thread.currentThread().getName() + ",生成订单id:" + number);
            } catch (Exception e) {
    
            } finally {
                extLock.unLock();
            }
        }
    
        public static void main(String[] args) {
            System.out.println("多线程生成number");
            // OrderService orderService = new OrderService();
            for (int i = 0; i < 100; i++) {
                new Thread(new OrderService()).start();
            }
        }
    
    }
    

    分布式锁解决方案.png

    zk实现分布式锁.png分布式锁引入.png
    java-zk_lock_2018.zip
    分布式协调工具-ZooKeeper.docx