Zookeeper实现分布式锁

利用ZooKeeper实现分布式锁.png
  • pom.xml
    
        
            junit
            junit
            3.8.1
            test
        

        
            org.apache.curator
            curator-framework
            4.0.0
        

        
            org.apache.curator
            curator-recipes
            4.0.0
        

        
            org.apache.curator
            curator-client
            4.0.0
        
        
            org.apache.zookeeper
            zookeeper
            3.4.6
        

        
            com.google.guava
            guava
            16.0.1
        

    
  • 案例代码
import org.apache.curator.RetryPolicy;
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.ExponentialBackoffRetry;

public class TestDemo {

    //定义共享资源
    private static int NUMBER = 10;
    //定义业务逻辑
    private static void printNumber() {
        System.out.println("*******秒杀开始********");
        System.out.println("当前数字:" + NUMBER);
        
        NUMBER--;
        
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("*******秒杀结束********\n");
    }
        
    public static void main(String[] args) {
        //定义重试策略
        RetryPolicy policy = new ExponentialBackoffRetry(1000, //每次重试等待时间
                                                         10);//重试的次数
        //定义ZooKeeper的客户
        CuratorFramework client = CuratorFrameworkFactory.builder()
                                                         .connectString("192.168.157.111:2181")
                                                         .retryPolicy(policy)
                                                         .build();
        client.start();
        
        //在ZooKeeper中创建锁
        final InterProcessMutex lock = new InterProcessMutex(client, "/mylock");
        
        //客户端
        for(int i=0;i<10;i++) {
            new Thread(new Runnable() {
                
                public void run() {
                    try {
                        //请求得到锁
                        lock.acquire();
                        
                        //执行秒杀
                        printNumber();
                    }catch(Exception ex) {
                        ex.printStackTrace();
                    }finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }
}

你可能感兴趣的:(Zookeeper实现分布式锁)