准备:在服务器上启动zkServer,引入jar包
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.14</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>3.1.0</version>
</dependency>
1、分布式锁
public class Main {
static String lock_path = "/curator_recipes_lock_path";
static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
.retryPolicy(new ExponentialBackoffRetry(1000,3)).build();
public static void main(String[] args) {
client.start();
final InterProcessLock lock = new InterProcessMutex(client,lock_path);
final CountDownLatch down = new CountDownLatch(1);
for (int i =0;i<30;i++){
new Thread(new Runnable() {
@Override
public void run() {
try {
down.await();
lock.acquire();
} catch (Exception e) {
e.printStackTrace();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss|SSS");
String orderNo = simpleDateFormat.format(new Date());
System.out.println("订单号:"+orderNo);
try {
lock.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
down.countDown();
}
}
2、原子计数器
public class Main {
static String distatomic_path = "/curator_recipes_distatomicint_path";
static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
public static void main(String[] args) throws Exception {
client.start();
DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(client, distatomic_path, new RetryNTimes(3, 1000));
AtomicValue<Integer> rc = atomicInteger.add(8);
System.out.println(rc.postValue());
System.out.println(rc.preValue());
System.out.println("Result:" + rc.succeeded());
}
}
3、类似于aqs的CyclicBarrier
public class Main {
static String barrier_path = "/curator_recipes_barrier_path";
static DistributedBarrier barrier;
static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
public static void main(String[] args) throws Exception {
client.start();
barrier = new DistributedBarrier(client, barrier_path);
for (int i = 0; i < 5; i++) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "号barrier" +
"设置");
try {
barrier.setBarrier();
barrier.waitOnBarrier();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("启动");
}
}).start();
}
Thread.sleep(3000);
barrier.removeBarrier();
}
}
仅用作学习记录