package com.huawei.buildcenter.taskschedule.impl.distributedlock;
/**
* The DistributedLock
*
* @author t00511139
* @version [ManageOne V100R006c50, 2020/12/22]
* @since 2020/12/22
*/
public interface DistributedLock {
/**
* 获取分布式锁
*
* @return 是否获取锁成功
*/
public boolean getLock();
/**
* 删除分布式锁
*/
public void unLock();
/**
* 等待获取锁
*/
public boolean waitLock();
}
package com.huawei.buildcenter.taskschedule.impl.distributedlock;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Value;
import java.util.concurrent.CountDownLatch;
/**
* The ZookeeperDistributedLock
*
* @author t00511139
* @version [ManageOne V100R006c50, 2020/12/22]
* @since 2020/12/22
*/
public class ZookeeperDistributedLock implements DistributedLock {
private String zookeeperPoint = "/lockPath";
private CountDownLatch countDownLatch = null;
@Override
public boolean getLock() {
try {
ZkClient zkClient = ZookeeperManager.getZkClient();
zkClient.createEphemeral(zookeeperPoint);
} catch (Exception e) {
return false;
}
return true;
}
@Override
public void unLock() {
ZkClient zkClient = ZookeeperManager.getZkClient();
if (zkClient != null) {
zkClient.delete(zookeeperPoint);
}
}
@Override
public boolean waitLock() {
ZkClient zkClient = ZookeeperManager.getZkClient();
IZkDataListener iZkDataListener = new IZkDataListener() {
@Override
public void handleDataChange(String s, Object o) throws Exception {
}
@Override
public void handleDataDeleted(String s) throws Exception {
if (countDownLatch != null) {
countDownLatch.countDown();
}
}
};
zkClient.subscribeDataChanges(zookeeperPoint, iZkDataListener);
if (zkClient.exists(zookeeperPoint)) {
countDownLatch = new CountDownLatch(1);
try {
countDownLatch.await();
} catch (Exception e) {
return false;
}
}
zkClient.unsubscribeDataChanges(zookeeperPoint, iZkDataListener);
return true;
}
}
package com.huawei.buildcenter.taskschedule.impl.distributedlock;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Value;
/**
* The ZookeeperManager
*
* @author t00511139
* @version [ManageOne V100R006c50, 2020/12/22]
* @since 2020/12/22
*/
public class ZookeeperManager {
private static String zookeeperAddress = "cloudbuildzk-stage.inhuawei.com:2181";
private static ZkClient zkClient = new ZkClient(zookeeperAddress);
public static ZkClient getZkClient() {
return zkClient;
}
}
public void scheduledTask() {
ZookeeperDistributedLock zookeeperDistributedLock = new ZookeeperDistributedLock();
String ipAddress = "";
try {
InetAddress address = InetAddress.getLocalHost();
ipAddress = address + " ";
} catch (Exception e) {
logger.error("Exception ", e);
}
if (zookeeperDistributedLock.getLock()) {
try {
//doTask();
logger.warn(ipAddress + "success get the key.");
Thread.sleep(5000);
} catch (Exception e) {
logger.error("Exception ", e);
} finally {
zookeeperDistributedLock.unLock();
}
} else {
logger.error(ipAddress + "fail get the key.");
}
}