分布式锁主要用于在分布式环境中保证数据的一致性。
包括跨进程、跨机器、跨网络导致共享资源不一致的问题。
分布式锁的实现思路
这种实现会有一个缺点,即当有很多进程在等待锁的时候,在释放锁的时候会有很多进程来争夺锁,这种现象称为“惊群效应”
分布式锁优化后的实现思路
分布式锁实现类 ImproveLock
public class ImproveLock implements Lock {
private static Logger logger = LoggerFactory.getLogger(ImproveLock.class);
private static final String ZOOKEEPER_IP_PORT = "10.143.143.185:6182";
private static final String LOCK_PATH = "/LOCK";
private ZkClient client = new ZkClient(ZOOKEEPER_IP_PORT, 10000, 10000, new SerializableSerializer());
private CountDownLatch cdl;
private String beforePath;// 当前请求的节点前一个节点
private String currentPath;// 当前请求的节点
// 判断有没有LOCK目录,没有则创建
public ImproveLock() {
if (!this.client.exists(LOCK_PATH)) {
this.client.createPersistent(LOCK_PATH);
}
}
public boolean tryLock() {
// 如果currentPath为空则为第一次尝试加锁,第一次加锁赋值currentPath
if (currentPath == null || currentPath.length() <= 0) {
// 创建一个临时顺序节点
currentPath = this.client.createEphemeralSequential(LOCK_PATH + '/', "lock");
System.out.println("---------------------------->" + currentPath);
}
// 获取所有临时节点并排序,临时节点名称为自增长的字符串如:0000000400
List 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 {
logger.info(Thread.currentThread().getName() + " 获得分布式锁!");
}
}
private void waitForLock() {
IZkDataListener listener = new IZkDataListener() {
public void handleDataDeleted(String dataPath) throws Exception {
logger.info(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;
}
}
自增长序列 OrderCodeGenerator
public class OrderCodeGenerator {
// 自增长序列
private static int i = 0;
// 按照“年-月-日-小时-分钟-秒-自增长序列”的规则生成订单编号
public String getOrderCode() {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
return sdf.format(now) + ++i;
}
public static void main(String[] args) {
OrderCodeGenerator ong = new OrderCodeGenerator();
for (int i = 0; i < 10; i++) {
System.out.println(ong.getOrderCode());
}
}
}
用10个线程去访问 OrderServiceImpl
public class OrderServiceImpl implements Runnable {
private static OrderCodeGenerator ong = new OrderCodeGenerator();
private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
// 同时并发的线程数
private static final int NUM = 10;
// 按照线程数初始化倒计数器,倒计数器
private static CountDownLatch cdl = new CountDownLatch(NUM);
// private static Lock lock = new ReentrantLock();
private Lock lock = new ImproveLock();
// 创建订单接口
public void createOrder() {
String orderCode = null;
lock.lock();
try {
// 获取订单编号
orderCode = ong.getOrderCode();
} catch (Exception e) {
// TODO: handle exception
} finally {
lock.unlock();
}
// ……业务代码,此处省略100行代码
logger.info("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 Thread(new OrderServiceImpl()).start();
// 创建一个线程,倒计数器减1
cdl.countDown();
}
}
}