分布式鎖-----秒殺系統
阿新 • • 發佈:2019-02-22
png off cat 當前 try 分布式鎖 lee framework tar
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
分布式鎖-----秒殺系統