• 6、zookeeper应用场景-分布式唯一ID


    分布式唯一id案例

      原理:使用zookeeper有序节点,节点后会加上有序的id,用这个id来当唯一ID

      在过去的单库单表型系统中,通常第可以使用数据库字段自带的auto_ increment属性来自动为每条记录生成个唯一的ID

    但是分库分表后,就无法在依靠数据库的auto_ increment属性来唯一标识一条记录了。此时我们就可以用zookeeper在分布式环境下生成全局唯一ID

     

    案例:

    public class IdGenerate {
    
        private static final String IP = "192.168.133.133:2181";
        private static CountDownLatch countDownLatch = new CountDownLatch(1);
        private static ZooKeeper zooKeeper;
    
        public static String generateId() throws Exception {
            return zooKeeper.create("/id", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        }
    
    
        public static void main(String[] args) throws Exception {
            zooKeeper = new ZooKeeper(IP, 5000, new ZKWatcher());
            countDownLatch.await();
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
            for (int i = 0; i < 10; i++) {
                threadPoolExecutor.execute(() -> {
                    try {
                        System.out.println(generateId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            TimeUnit.SECONDS.sleep(50);
            threadPoolExecutor.shutdown();
        }
    
        static class ZKWatcher implements Watcher {
            @Override
            public void process(WatchedEvent watchedEvent) {
                countDownLatch.countDown();
                System.out.println("zk的监听器" + watchedEvent.getType());
            }
        }
    }
  • 相关阅读:
    intellij idea的Maven项目运行报程序包找不到的错误
    修改Maven项目默认JDK版本
    Android学习_MVC与Adapter
    Android学习_Selector
    Android学习_内容提示器
    Android学习_Fragment
    Android学习_服务
    Android学习_数据持久化
    Android学习_广播接收器
    Git与Repo 的使用
  • 原文地址:https://www.cnblogs.com/lemon-flm/p/14605376.html
Copyright © 2020-2023  润新知