欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-22 12:42:10
复制代码 代码如下:import java.util.concurrent.countdownlatch;import java.util.concurrent.execu...

复制代码 代码如下:

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();
   }
   }
 }
 }