当前位置: 移动技术网 > IT编程>开发语言>Java > 使用curator实现zookeeper锁服务的示例分享

使用curator实现zookeeper锁服务的示例分享

2019年07月22日  | 移动技术网IT编程  | 我要评论

复制代码 代码如下:

import java.util.concurrent.countdownlatch;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.timeunit;

import com.netflix.curator.retrypolicy;
import com.netflix.curator.framework.curatorframework;
import com.netflix.curator.framework.curatorframeworkfactory;
import com.netflix.curator.framework.recipes.locks.interprocessmutex;
import com.netflix.curator.retry.exponentialbackoffretry;

public class testcuratorlock {

 /**
  * @param args
  * @throws interruptedexception
  */
 public static void main(string[] args) throws interruptedexception {
  // todo auto-generated method stub

  countdownlatch latch = new countdownlatch(5);

  string zookeeperconnectionstring = "localhost:2181,localhost:2182,localhost:2183";
  retrypolicy retrypolicy = new exponentialbackoffretry(1000, 3);
  curatorframework client = curatorframeworkfactory.newclient(
    zookeeperconnectionstring, retrypolicy);
  client.start();
  system.out.println("客户端启动。。。。");
  executorservice exec = executors.newcachedthreadpool();

  for (int i = 0; i < 5; i++) {
   exec.submit(new mylock("client" + i, client, latch));
  }

  exec.shutdown();
  latch.await();
  system.out.println("所有任务执行完毕");

  client.close();

  system.out.println("客户端关闭。。。。");

 }

 static class mylock implements runnable {

  private string name;

  private curatorframework client;

  private countdownlatch latch;

  public mylock(string name, curatorframework client, countdownlatch latch) {
   this.name = name;
   this.client = client;
   this.latch = latch;
  }

  public string getname() {
   return name;
  }

  public void setname(string name) {
   this.name = name;
  }

  @override
  public void run() {
   // todo auto-generated method stub
   interprocessmutex lock = new interprocessmutex(client,
     "/test_group");
   try {
    if (lock.acquire(120, timeunit.seconds)) {
     try {
      // do some work inside of the critical section here
      system.out.println("----------" + this.name
        + "获得资源----------");
      system.out.println("----------" + this.name
        + "正在处理资源----------");
      thread.sleep(10 * 1000);
      system.out.println("----------" + this.name
        + "资源使用完毕----------");
      latch.countdown();
     } finally {
      lock.release();
      system.out.println("----------" + this.name
        + "释放----------");
     }
    }
   } catch (exception e) {
    // todo auto-generated catch block
    e.printstacktrace();
   }
   }
 }
 }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网