试想一下如果有一百台机子,同时去修改一个配置文件,要保证这个文件不被乱写,这就需要用到分布式锁。
前面部署的zk集群现在可以用了,那么我们来看看分布式锁的原理:
分布式锁的思路
缺点:“惊群效应”
优化后的算法:
然后上代码:
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyLockimplements Lock {
private static Logger logger = LoggerFactory.getLogger(ImproveLock.class);
private static final String ZOOKEEPER_IP_PORT = "192.168.1.49:2181";//这里是我的zk服务器地址
private static final String LOCK_PATH = "/lock";//目录名称
private ZkClient client = new ZkClient(ZOOKEEPER_IP_PORT, 1000, 1000,
new SerializableSerializer());//创建zk客户端
private CountDownLatch cdl;
private String beforePath; // 当前请求的节点前一个节点
private String currentPath; // 当前请求的节点
// 在创建锁的时候初始化这个目录
public ImproveLock() {
if (!this.client.exists(LOCK_PATH)) {
this.client.createPersistent(LOCK_PATH);
}
}
/*试图加锁,注意一定要创建临时顺序节点、临时节点是随着会话的断开会自动 顺序节点是为了让 后面一个节点可以监听前一个节点是否有删除的操作,如果删除了就通知后面的节点去获取锁,避免所有的节点都去获取锁(惊群效应)*/
public boolean tryLock() {
if (currentPath == null || currentPath.length() <= 0) {
// 创建一个临时顺序节点 注意一定要创建临时顺序节点
currentPath = this.client.createEphemeralSequential(LOCK_PATH + '/', "lock");
System.out.println("---------------------------->" + currentPath);
}
// 获取所有临时节点并排序,临时节点名称为自增长的字符串如:0000000400
List<String> childrens = this.client.getChildren(LOCK_PATH);
Collections.sort(childrens);
if (currentPath.equals(LOCK_PATH + '/' + childrens.get(0))) {// 如果当前节点在所有节点中排名第一则获取锁成功
return true;
} else {// 节点中排名中不是排名第一,则获取前面的节点名称,并赋值给beforePath 这个是做监听前面节点的删除
int wz = Collections.binarySearch(childrens, currentPath.substring(6));
beforePath = LOCK_PATH + '/' + childrens.get(wz - 1);
}
return false;
}
public void unlock() {
// 删除当前临时节点
client.delete(currentPath);
}
public void lock() {
if (!tryLock()) {
waitForLock();
lock();
} else {
System.out.println(Thread.currentThread().getName() + " 获得分布式锁!==" + currentPath);
}
}
private void waitForLock() {
IZkDataListener listener = new IZkDataListener() {
public void handleDataDeleted(String dataPath) throws Exception {
System.out.println(Thread.currentThread().getName()
+ ":捕获到DataDelete事件!---------------------------");
if (cdl != null) {
cdl.countDown();
}
}
public void handleDataChange(String dataPath, Object data) throws Exception {
}
};
// 给排在前面的的节点增加数据删除的watcher
this.client.subscribeDataChanges(beforePath, listener);
if (this.client.exists(beforePath)) {
cdl = new CountDownLatch(1);
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.client.unsubscribeDataChanges(beforePath, listener);
}
// ==========================================
public void lockInterruptibly() throws InterruptedException {
}
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
public Condition newCondition() {
return null;
}
}
思考一下上面的tryLock() waitForLock()没有同步会不会有线程安全问题
测试一下:
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrderServiceImpl implements Runnable {
//为什么每次new的i的值还自增、因为用static修饰的成员变量是一个实例
private static OrderCodeGenerator ong = new OrderCodeGenerator();
private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);// 同时并发的线程数
private static final int NUM = 50;
// 按照线程数初始化倒计数器,倒计数器
private static CountDownLatch cdl = new CountDownLatch(NUM);
// private static Lock lock = new ReentrantLock();
private Lock lock = new MyLock();//这里new了一个锁
// 创建订单接口
public void createOrder() {
String orderCode = null;
lock.lock();
try {
// 获取订单编号
orderCode = ong.getOrderCode();
} catch (Exception e) {
// TODO: handle exception
} finally {
lock.unlock();
}
System.out.println("insert into DB使用id:=======================>" + orderCode);
}
@Override
public void run() {
try {
// 等待其他线程初始化
cdl.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 创建订单
createOrder();
}
public static void main(String[] args) {
for (int i = 1; i <= NUM; i++) {
//这里可以看出是new的对象 所有MyLock每个对象都是新的 自己搞自己的对象是没问题的
new Thread(new OrderServiceImpl()).start();
// 创建一个线程,倒计数器减1cdl.countDown();
}
}
}
如有不对之处欢迎指正