分布式锁-----秒杀系统
1.ZK
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 TestZK { //定义共享资源 private static int NUMBER = 10; private static void getNumber(){ System.out.println("*********业务方法开始*********"); System.out.println("当前值:"+NUMBER); NUMBER--; try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("*********业务方法结束*********"); } public static void main(String[] args) { //定义retrypolicy 重试策略 RetryPolicy policy = new ExponentialBackoffRetry(1000, //等待的时间 10);//重试的测试 //定义ZK的客户端 CuratorFramework client = CuratorFrameworkFactory.builder() .connectString("192.168.56.111:2181") .retryPolicy(policy) .build(); client.start(); //定义锁 final InterProcessMutex lock = new InterProcessMutex(client,"/mylock"); for(int i=0;i<10;i++){ new Thread(new Runnable() { public void run() { try { //请求锁 lock.acquire(); // 访问业务方法 getNumber(); } catch (Exception e) { e.printStackTrace(); }finally{ try { lock.release(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } } }
2.Redis