• 基于Curator的zookeeper分布式锁


    导入依赖

      

    <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
    <dependency>
        <groupId>org.apache.curator</groupId>
        <artifactId>curator-recipes</artifactId>
        <version>4.2.0</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-framework -->
    <dependency>
        <groupId>org.apache.curator</groupId>
        <artifactId>curator-framework</artifactId>
        <version>4.2.0</version>
    </dependency>
    import org.apache.curator.framework.CuratorFramework;
    import org.apache.curator.framework.CuratorFrameworkFactory;
    import org.apache.curator.framework.recipes.locks.InterProcessMutex;
    import org.apache.curator.retry.RetryNTimes;
    
    import java.util.concurrent.TimeUnit;
    
    /**
     * Curator framework's distributed lock test.
     */
    public class CuratorDistrLockTest {
    
        /** Zookeeper info */
        private static final String ZK_ADDRESS = "192.168.1.100:2181";
        private static final String ZK_LOCK_PATH = "/zktest";
    
        public static void main(String[] args) throws InterruptedException {
            // 1.Connect to zk
            CuratorFramework client = CuratorFrameworkFactory.newClient(
                    ZK_ADDRESS,
                    new RetryNTimes(10, 5000)
            );
            client.start();
            System.out.println("zk client start successfully!");
    
            Thread t1 = new Thread(() -> {
                doWithLock(client);
            }, "t1");
            Thread t2 = new Thread(() -> {
                doWithLock(client);
            }, "t2");
    
            t1.start();
            t2.start();
        }
    
        private static void doWithLock(CuratorFramework client) {
            InterProcessMutex lock = new InterProcessMutex(client, ZK_LOCK_PATH);
            try {
                if (lock.acquire(10 * 1000, TimeUnit.SECONDS)) {
                    System.out.println(Thread.currentThread().getName() + " hold lock");
                    Thread.sleep(5000L);
                    System.out.println(Thread.currentThread().getName() + " release lock");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 相关阅读:
    回调函数仿360开机
    封装运动框架基本函数(多个属性包括透明度和zIndex)
    封装运动框架基本函数(单个属性)
    返回当前样式的函数
    MacOs High Sierra 升级失败解决办法
    Easy-RSA 3 Quickstart README
    Easily use UUIDs in Laravel
    OAuth2.0 原理流程及其单点登录和权限控制
    细说SSO单点登录
    单点登录
  • 原文地址:https://www.cnblogs.com/jikeyi/p/13592325.html
Copyright © 2020-2023  润新知