admin 管理员组

文章数量: 887021


2024年2月19日发(作者:干组词100个)

基于Zookeeper的锁应用开发手册

基于Zookeeper的锁应用开发手册

版本 <1.0>

1

基于Zookeeper的锁应用开发手册

修订历史

日期

2013-10-25

版本

1.0

描述

基于Zookeeper的锁应用开发手册

苏晓辉

修改人

2

基于Zookeeper的锁应用开发手册

基于Zookeeper的锁应用开发手册 ................................................................................................ 4

1 概述 .............................................................................................................................................. 4

1.1 前言 ............................................................................................................................... 4

1.2 目的 ............................................................................................................................... 4

1.3 范围 ............................................................................................................................... 4

1.4 术语和缩写语 ............................................................................................................... 4

2 排他锁........................................................................................................................................... 5

3 共享锁........................................................................................................................................... 6

4 数据库锁....................................................................................................................................... 7

5 总结和展望 ................................................................................................................................... 8

6 附件代码....................................................................................................................................... 9

7 参考资料..................................................................................................................................... 36

3

基于Zookeeper的锁应用开发手册

基于Zookeeper的锁应用开发手册

1 概述

1.1 前言

Zookeeper是Hadoop的正式子项目,它是一个针对大型分布式系统的可靠协调系统,提供的功能包括:配置维护、名字服务、分布式同步、组服务等。Zookeeper的目标就是封装好复杂易出错的关键服务,将简单易用的接口和性能高效、功能稳定的系统提供给用户。

1.2 目的

本文档的目的是帮助PAAS平台开发人员快速使用锁API,开发分布式系统中模块之间需要协同执行的相关的应用程序。本文第二、三、四章分别介绍排他锁、共享锁和数据库锁的功能和使用。最后,第五、六、七章给出附件代码、总结及展望和参考资料。

1.3 范围

本文档适用于PAAS系统整个项目周期中对模块之间需要协同执行的应用程序开发的指导和约束。要了解Zookeeper的使用详情,参考Zookeeper3.4.5官方文档。

1.4 术语和缩写语

术语

Zookeeper

PAAS

SAAS

说明

Zookeeper是Hadoop的正式子项目,它是一个针对大型分布式系统的可靠协调系统。

Platform-as-a-Service的缩写,意思是平台即服务。

把服务器平台作为一种服务提供的商业模式。

software-as-a-Service的缩写。国外称为SAAS,国内通常叫做软件运营服务模式,简称为软营模式。

4

基于Zookeeper的锁应用开发手册

2 排他锁

排他锁的实现机制是当一个线程获取锁后,另一个线程无法获取该锁,并报出异常,这里的线程可以在不同的JVM中;目前支持重入特性,在同一线程中的不同地方(不同的方法中)可以重复获取同一把锁。

排他锁的使用场景是当一个线程需要对分布式系统中的某些资源独占,不希望其它线程对该资源进行操作。

排他锁使用范例如下代码所示,如果代码()获取锁key1锁,则进入独占资源操作代码,否则进入异常处理代码,最后释放锁()。

MutexLock lock = null;

try {

lock = new MutexLockImplZooKeeper("127.0.0.1:2181", "key1");

();

//独占资源操作代码

} catch (LockException e) {

//异常处理代码

} finally {

}

try {if(lock!=null) ();} catch (LockException e) {}

5

基于Zookeeper的锁应用开发手册

3 共享锁

共享锁有读锁和写锁两种状态,共享锁的实现机制是当一个线程获取锁的读状态后,另一个线程也可以获取该锁的读状态,但是另一个线程无法获取该锁的写状态,并抛出异常;当一个线程获取锁的写状态后,另一个线程无法获取该锁,并抛出异常。这里的线程可以在不同的JVM中;目前支持重入特性,在同一线程中的不同地方(不同的方法中)可以重复获取同一把锁。

共享锁的使用场景是当一个线程需要对分布式系统中的某些资源进行读取操作时,其它线程也可以读取该资源,但是不能进行写操作;当一个线程需要对分布式系统中的某些资源进行写操作时,不希望其它线程对该资源进行操作。

共享锁使用范例如下代码所示,如果代码()/()获取锁key1锁,则进入独占资源操作代码,否则进入异常处理代码,最后释放锁()。

SharedLocklock = null;

try {

lock = new SharedLockImplZooKeeper ("127.0.0.1:2181", "key1");

();//();

//独占资源操作代码

} catch (LockException e) {

//异常处理代码

} finally {

}

try {if(lock!=null) ();} catch (LockException e) {}

6

基于Zookeeper的锁应用开发手册

4 数据库锁

目前数据库锁支持4种标准的数据库隔离等级,包括Read Uncommit、Read

Commit、No Repeating和Serialize,目前不支持锁的重入功能。

数据库锁的使用场景是需要提供数据库事务ACID特性的地方。

数据库锁使用范例如下代码所示,如果代码readLock("group1", "table1")/

writeLock("group1", " table1", "ID")获取数据库表锁或行锁,否则进入异常处理代码,最后释放锁release()。

DBLockImplZooKeeper lock = null;

try {

lock = new DBLockImplZooKeeper("127.0.0.1:2181");

//or new DBLockImplZooKeeper("127.0.0.1:2181",

//or new DBLockImplZooKeeper("127.0.0.1:2181", 3, 100, 10000,

ck("group1", "table1");

//操作代码

ock("group1", " table1", "ID");

//操作代码

//异常处理代码

} finally {

}

try {if(lock!=null) e();} catch (LockException e) {}

} catch (LockException e) {

MMIT);

MMIT);

7

基于Zookeeper的锁应用开发手册

5 总结和展望

将来可能还需要实现两阶段关闭(two phase temiate)锁来协同多个模块完成同一个工作,最后各模块要么一起成功,要么一起失败。

8

基于Zookeeper的锁应用开发手册

6 附件代码

//(c) Copyright Beyond PAAS contributors and others 2013

package ;

/**

* SharedLock is interface.

* @author su xiaohui

* @CreateDate 2013-10-18

*/

public interface SharedLock {

}

/**

* To get write lock

* @throws LockException

*/

void write()throws LockException;

/**

* To get read lock

* @throws LockException

*/

void read()throws LockException;

/**

* To release lock

* @throws LockException

*/

void close() throws LockException;

//(c) Copyright Beyond PAAS contributors and others 2013

package ;

import ption;

import ist;

import tions;

import ator;

import t;

9

基于Zookeeper的锁应用开发手册

import ;

import ;

import ;

import Mode;

import Exception;

import per;

import ;

/**

* SharedLockImplZooKeeper is threadSafed, so the class can't be extended and modified. On the

other hand,

* private and final and synchronized keywords can't be remove and modified by other keywords

except to

* you are sure that the class is threadSafed.

* SharedLockImplZooKeeper provide read-write lock function and support lock's reenter

function.

* SharedLockImplZooKeeper depends on the zookeeper severs, so you must be sure that

zookeeper servers

* are work.

* usage:

SharedLock l = null;

try {

l = new SharedLock("127.0.0.1:2181", "key1");

//or new SharedLock("127.0.0.1:2181", "key1", 3, 100, 10000);

...

();

//or ();

...

} catch (LockException e) {

...

} finally {

try {

if(l!=null) ();

} catch (LockException e) {}

10

基于Zookeeper的锁应用开发手册

}

* @author su xiaohui

* @CreateDate 2013-10-18

*/

final public class SharedLockImplZooKeeper implements SharedLock{

final private String root = "/shared";

final private String serverAddress;

final private String ownID;

final private int retry;

final private int waitTime;

final private int timeout;

private boolean isReentry;

private int count;

private int step;

private ZooKeeper zk;

final private String zookeeperID;

final static private ThreadLocal> session = new ThreadLocal>();

/**

* Construction

* @param serverAddress. Zookeeper servers' address-port like

'127.0.0.1:2181,127.0.0.2:2181,...'.

* @param ownID. Source Key or lock name.

* @throws LockException

*/

public SharedLockImplZooKeeper(String serverAddress, String ownID) throws LockException

{

this(serverAddress, ownID, 0, 100, 10000);

}

11

基于Zookeeper的锁应用开发手册

/**

* Construction

* @param serverAddress. Zookeeper servers' address-port like

'127.0.0.1:2181,127.0.0.2:2181,...'.

* @param ownID. Source Key or lock name.

* @param retry. Retry times.

* @param waitTime. Wait time.

* @param timeout. Time out.

* @throws LockException

*/

public SharedLockImplZooKeeper(String serverAddress, String ownID, int retry, int waitTime,

int timeout) throws LockException{

Address = serverAddress;

= ownID;

= retry;

me = waitTime;

t = timeout;

= 1;

= 0;

perID = UUID().toString();

}

private void init(String type) throws LockException{

if(("read")){

if(()==null || (!().contains(ownID+"_write")

&& !().contains(ownID+"_read")) ){

connectZooKeeper();

Set set = ()==null ? new HashSet() : ();

(ownID+"_read");

(set);

isReentry = false;

}else{

isReentry = true;

}

}else if(("write")){

if(()==null || !().contains(ownID+"_write") ){

if(()!=null && ().contains(ownID+"_read")){

throw new LockException(new Exception("The lock has been locked."));

12

基于Zookeeper的锁应用开发手册

}

}

}

connectZooKeeper();

Set set = ()==null ? new HashSet() : ();

(ownID+"_write");

(set);

isReentry = false;

}else{

isReentry = true;

}

@Override

synchronized public void write() throws LockException {

if(step!=1)

throw new LockException(new Exception("This lock is invalid."));

else

step = 2;

init("write");

while(true && !isReentry){

count++;

try{

executeWrite();

break;

}catch(LockException ex){

if(count>=retry){

closeLocalThread();

closeZookeeper();

throw new LockException(ex);

}else

try{(waitTime);}catch(Exception e){}

}

}

}

13

基于Zookeeper的锁应用开发手册

private void executeWrite() throws LockException{

String path = createPath();

String actualPath = "";

try {

actualPath = (path+"/"+ownID+"###"+zookeeperID+"###write###", new

byte[0], _ACL_UNSAFE, RAL_SEQUENTIAL);

List list1 = ldren(path, null);

List list2 = new ArrayList();

for(String node : list1){

if(("###").length==4) (node);

}

(list2,new Comparator(){

@Override

public int compare(String node1, String node2) {

String[] node1s = ("###");

String[] node2s = ("###");

if(ong(node1s[3])>ong(node2s[3]))

return 1;

if(ong(node1s[3])

return -1;

return 0;

}

});

for(String node : list2)

if(f(ownID)>-1)

if(f(zookeeperID)==-1)

throw new LockException(new Exception("The lock has been

locked."));

else

break;

} catch (KeeperException e) {

throw new LockException(e);

} catch (InterruptedException e) {

14

基于Zookeeper的锁应用开发手册

throw new LockException(e);

} catch (LockException e) {

if(actualPath!=null)

try {

(actualPath, 0);

} catch (InterruptedException e1) {

} catch (KeeperException e1) {

}

throw e;

}

}

@Override

public void read() throws LockException {

if(step!=1)

throw new LockException(new Exception("This lock is invalid."));

else

step = 2;

init("read");

while(true && !isReentry){

count++;

try{

executeRead();

break;

}catch(LockException ex){

if(count>=retry){

closeLocalThread();

closeZookeeper();

throw new LockException(ex);

}else

try{(waitTime);}catch(Exception e){}

}

}

}

private void executeRead() throws LockException {

15

基于Zookeeper的锁应用开发手册

String path = createPath();

String actualPath = "";

try {

actualPath = (path+"/"+ownID+"###"+zookeeperID+"###read###", new

byte[0], _ACL_UNSAFE, RAL_SEQUENTIAL);

List list1 = ldren(path, null);

List list2 = new ArrayList();

for(String node : list1){

if(("###").length==4) (node);

}

(list2,new Comparator(){

@Override

public int compare(String node1, String node2) {

String[] node1s = ("###");

String[] node2s = ("###");

if(ong(node1s[3])>ong(node2s[3]))

return 1;

if(ong(node1s[3])

return -1;

return 0;

}

});

for(String node : list2)

if(f(ownID)>-1){

if(f(zookeeperID)==-1){

if(f("###write###")>-1)

throw new LockException(new Exception("The lock has been

write locked."));

}else{

break;

}

}

} catch (KeeperException e) {

throw new LockException(e);

} catch (InterruptedException e) {

16

基于Zookeeper的锁应用开发手册

throw new LockException(e);

} catch (LockException e) {

if(actualPath!=null)

try {

(actualPath, -1);

} catch (InterruptedException e1) {

} catch (KeeperException e1) {

}

throw e;

}

}

private String createPath(){

try{

if((root, false)==null){

(root, new byte[0], _ACL_UNSAFE,

TENT);

}

} catch (KeeperException e) {} catch (InterruptedException e) {}

return root;

}

private void connectZooKeeper()throws LockException {

try {

if(zk==null) zk = new ZooKeeper(serverAddress, timeout, null);

} catch (IOException e) {

throw new LockException(e);

}

}

private void closeLocalThread(){

if(!isReentry && ()!=null){

().remove(ownID+"_write");

().remove(ownID+"_read");

}

}

private void closeZookeeper(){

17

基于Zookeeper的锁应用开发手册

}

}

if(zk!=null)

try {

();

} catch (InterruptedException e) {

}finally{

zk = null;

}

@Override

synchronized public void close() throws LockException {

if(step!=2)

throw new LockException(new Exception("The lock is invalid"));

else

step = 3;

closeLocalThread();

closeZookeeper();

}

//(c) Copyright Beyond PAAS contributors and others 2013

package ;

/**

* MutexLock is interface.

* @author su xiaohui

* @CreateDate 2013-10-18

*/

public interface MutexLock {

/**

* To get lock

* @throws LockException

*/

void lock() throws LockException;

/**

* To release lock

* @throws LockException

18

基于Zookeeper的锁应用开发手册

}

*/

void close() throws LockException;

//(c) Copyright Beyond PAAS contributors and others 2013

package ;

import ption;

import t;

import ;

import Mode;

import Exception;

import per;

import ;

/**

* MutexLockImplZooKeeper is threadSafed, so the class can't be extended and modified. On the

other hand,

* private and final and synchronized keywords can't be remove and modified by other keywords

except to

* you are sure that the class is threadSafed.

* MutexLockImplZooKeeper provide mutual lock function and support lock's reenter function.

* MutexLockImplZooKeeper depends on the zookeeper severs, so you must be sure that

zookeeper servers

* are work.

* usage:

MutexLock l = null;

try {

l = new MutexLockImplZooKeeper("127.0.0.1:2181", "key1");

//or l = new MutexLockImplZooKeeper("127.0.0.1:2181", "key1", 3, 100, 10000);

...

();

...

} catch (LockException e) {

19

基于Zookeeper的锁应用开发手册

...

} finally {

try {

if(l!=null) ();

} catch (LockException e) {}

}

* @author su xiaohui

* @CreateDate 2013-10-18

*/

final public class MutexLockImplZooKeeper implements MutexLock{

final private String root = "/mutex";

final private String serverAddress;

final private String ownID;

final private int retry;

final private int waitTime;

final private int timeout;

private boolean isReentry;

private int count;

private int step;

private ZooKeeper zk;

final private static ThreadLocal> session = new ThreadLocal>();

/**

* Construction

* @param serverAddress. Zookeeper servers' address-port like

'127.0.0.1:2181,127.0.0.2:2181,...'.

* @param ownID. Source Key or lock name.

* @throws LockException

*/

20

基于Zookeeper的锁应用开发手册

public MutexLockImplZooKeeper(String serverAddress, String ownID) throws LockException

{

this(serverAddress, ownID, 0, 100, 10000);

}

/**

* Construction

* @param serverAddress. Zookeeper servers' address-port like

'127.0.0.1:2181,127.0.0.2:2181,...'.

* @param ownID. Source Key or lock name.

* @param retry. Retry times.

* @param waitTime. Wait time.

* @param timeout. Time out.

* @throws LockException

*/

public MutexLockImplZooKeeper(String serverAddress, String ownID, int retry, int waitTime,

int timeout) throws LockException{

Address = serverAddress;

= ownID;

= retry;

me = waitTime;

t = timeout;

= 1;

= 0;

}

@Override

synchronized public void lock() throws LockException {

if(step!=1)

throw new LockException(new Exception("This lock is invalid."));

else

step = 2;

init();

while(true && !isReentry){

count++;

try{

execute();

break;

21

基于Zookeeper的锁应用开发手册

}catch(LockException ex){

if(count>=retry){

closeLocalThread();

closeZookeeper();

throw new LockException(ex);

}else

try{(waitTime);}catch(Exception e){}

}

}

}

private void init() throws LockException{

if(()==null || !().contains(ownID)){

connectZooKeeper();

Set set = ()==null ? new HashSet() : ();

(ownID);

(set);

isReentry = false;

}else{

isReentry = true;

}

}

private void execute() throws LockException{

try {

(createPath(), new byte[0], _ACL_UNSAFE,

RAL);

} catch (KeeperException e) {

throw new LockException(e);

} catch (InterruptedException e) {

throw new LockException(e);

}

}

private String createPath(){

try{

if((root, false)==null){

22

基于Zookeeper的锁应用开发手册

(root, new byte[0], _ACL_UNSAFE,

TENT);

}

} catch (KeeperException e) {} catch (InterruptedException e) {}

return root+"/"+ownID;

}

private void connectZooKeeper()throws LockException {

try {

if(zk==null) zk = new ZooKeeper(serverAddress, timeout, null);

} catch (IOException e) {

throw new LockException(e);

}

}

private void closeLocalThread(){

if(!isReentry && ()!=null){

if(().contains(ownID)) ().remove(ownID);

}

}

private void closeZookeeper(){

if(zk!=null)

try {

();

} catch (InterruptedException e) {

}finally{

zk = null;

}

}

@Override

synchronized public void close() throws LockException {

if(step!=2)

throw new LockException(new Exception("This lock is invalid."));

else

step = 3;

closeLocalThread();

23

基于Zookeeper的锁应用开发手册

}

}

closeZookeeper();

//(c) Copyright Beyond PAAS contributors and others 2013

package ;

/**

* DBLock is interface.

* @author su xiaohui

* @CreateDate 2013-10-25

*/

public interface DBLock {

/**

* To get read lock

* @param group. It is group name, which is often organization name.

* @param table. It is table name.

* @param id. It is a primary key, which is often uuid.

* @throws LockException

*/

void readLock(String group, String table, String id) throws LockException;

/**

* To get write lock

* @param group. It is group name, which is often organization name.

* @param table. It is table name.

* @throws LockException

*/

void writeLock(String group, String table) throws LockException;

/**

24

enum IsolateLevel {READUNCOMMIT, READCOMMIT, NOREPEAT, SERIALIZE};

/**

* To get read lock

* @param group. It is group name, which is often organization name.

* @param table. It is table name.

* @throws LockException

*/

void readLock(String group, String table) throws LockException;

基于Zookeeper的锁应用开发手册

}

* To get write lock

* @param group. It is group name, which is often organization name.

* @param table. It is table name.

* @param id. It is a primary key, which is often uuid.

* @throws LockException

*/

void writeLock(String group, String table, String id) throws LockException;

/**

* To release lock

* @throws LockException

*/

void release() throws LockException;

//(c) Copyright Beyond PAAS contributors and others 2013

package ;

import ption;

import ist;

import tions;

import ator;

import ;

import ;

import Mode;

import Exception;

import per;

import ;

import ;

/**

* DBLockImplZooKeeper is threadSafed, so the class can't be extended and modified. On the

other hand,

* private and final and synchronized keywords can't be remove and modified by other keywords

except to

* you are sure that the class is threadSafed.

* DBLockImplZooKeeper support 4 type of transaction isolate level.

* DBLockImplZooKeeper depends on the zookeeper severs, so you must be sure that zookeeper

servers

* are work.

* usage:

25

基于Zookeeper的锁应用开发手册

DBLockImplZooKeeper l = null;

try {

l = new DBLockImplZooKeeper("127.0.0.1:2181");

//or new DBLockImplZooKeeper("127.0.0.1:2181", MMIT);

//or new DBLockImplZooKeeper("127.0.0.1:2181", 3, 100, 10000,

MMIT);

...

ck("test", "t1", "*");

...

ock("test", "t1", "100");

...

} catch (LockException e) {

...

} finally {

try {

if(l!=null) e();

} catch (LockException e) {}

}

* @author su xiaohui

* @CreateDate 2013-10-18

*/

final public class DBLockImplZooKeeper implements DBLock{

final private String root = "/dblock";

final private String serverAddress;

final private String ownID;

final private int retry;

final private int waitTime;

26

基于Zookeeper的锁应用开发手册

final private int timeout;

final private IsolateLevel isolationLevel;

private int count;

private int step;

private ZooKeeper zk;

final private List paths = new ArrayList();

/**

* Constructor

* @param serverAddress. Zookeeper servers' address-port like

'127.0.0.1:2181,127.0.0.2:2181,...'.

* @param ownID. Source Key or lock name.

*/

public DBLockImplZooKeeper(String serverAddress){

this(serverAddress, 3, 100, 10000, MMIT);

}

/**

* Constructor

* @param serverAddress. Zookeeper servers' address-port like

'127.0.0.1:2181,127.0.0.2:2181,...'.

* @param ownID. Source Key or lock name.

* @param isolationLevel。Transation isolate level

*/

public DBLockImplZooKeeper(String serverAddress, IsolateLevel isolationLevel){

this(serverAddress, 3, 100, 10000, isolationLevel);

}

/**

* Construction

* @param serverAddress. Zookeeper servers' address-port like

'127.0.0.1:2181,127.0.0.2:2181,...'.

* @param ownID. Source Key or lock name.

* @param retry. Retry times.

* @param waitTime. Wait time.

* @param timeout. Time out.

27

基于Zookeeper的锁应用开发手册

* @param isolationLevel. Transation isolate level

* @throws LockException

*/

public DBLockImplZooKeeper(String serverAddress, int retry, int waitTime, int timeout,

IsolateLevel isolationLevel){

Address = serverAddress;

= UUID().toString();

= retry;

me = waitTime;

t = timeout;

ionLevel = isolationLevel;

= 1;

}

@Override

public void readLock(String group, String table)

throws LockException {

readLock(group, table, null);

}

@Override

public void readLock(String group, String table, String id)

throws LockException {

if(step!=1) throw new LockException(new Exception("This lock is invalid."));

if(group==null || ().equals("")) throw new NullPointerException("Group is

null.");

if(table==null || ().equals("")) throw new NullPointerException("Table is

null.");

connectZooKeeper();

while(true){

count++;

try{

execute(group, table, id, "read");

break;

}catch(LockException ex){

if(count>=retry){

28

基于Zookeeper的锁应用开发手册

release();

throw new LockException(ex);

}

else

try{(waitTime);}catch(Exception e){}

}

}

count = 0;

}

@Override

public void writeLock(String group, String table)

throws LockException {

writeLock(group, table, null);

}

@Override

public void writeLock(String group, String table, String id)

throws LockException {

if(step!=1) throw new LockException(new Exception("This lock is invalid."));

if(group==null || ().equals("")) throw new NullPointerException("Group is

null.");

if(table==null || ().equals("")) throw new NullPointerException("Table is

null.");

connectZooKeeper();

while(true){

count++;

try{

execute(group, table, id, "write");

break;

}catch(LockException ex){

if(count>=retry){

release();

throw new LockException(ex);

29

基于Zookeeper的锁应用开发手册

}

else

try{(waitTime);}catch(Exception e){}

}

}

count = 0;

}

private void execute(String group, String table, String id, String operation) throws

LockException {

String path = createPath(group, table);

String actualPath = "";

if(id==null || ().equals("")) id = "*";

try {

String level = "";

if(isolationLevel==COMMIT){

level = "RU";

}else if(isolationLevel==MMIT){

level = "RC";

}else if(isolationLevel==AT){

level = "NR";

}else if(isolationLevel==IZE){

level = "SL";

}

String newNode = id+"###"+operation+"###"+ownID+"###"+level;

actualPath = (path+"/"+newNode+"###", new byte[0],

_ACL_UNSAFE, RAL_SEQUENTIAL);

List list1 = ldren(path, null);

List list2 = new ArrayList();

for(String node : list1){

if(("###").length==5) (node);

}

(list2,new Comparator(){

@Override

public int compare(String node1, String node2) {

String[] node1s = ("###");

30

基于Zookeeper的锁应用开发手册

}

/*

});

}

String[] node2s = ("###");

if(ong(node1s[4])>ong(node2s[4]))

return 1;

if(ong(node1s[4])

return -1;

return 0;

for(String oldNode : list2){

String[] olds = ("###");

String[] news = ("###");

if(!olds[2].equals(news[2])){

checkPrivilege(olds, news);

checkPrivilege(news, olds);

}else{

if(hasPrivilege(olds, news)) break;

}

}

} catch (KeeperException e) {

throw new LockException(e);

} catch (InterruptedException e) {

throw new LockException(e);

} catch (LockException e) {

if(actualPath!=null)

try {

(actualPath, -1);

} catch (InterruptedException e1) {

} catch (KeeperException e1) {

}

throw e;

}

if(!ns(path)) (path);

31

基于Zookeeper的锁应用开发手册

* array[0] is id

* array[1] is operation

* array[2] is ownID

* array[3] is isolate level

*/

private void checkPrivilege(String[] in, String[] off) throws LockException{

if(in[0].equals("*") || in[0].equals(off[0]) || off[0].equals("*"))

if(in[3].equals("RU") && in[1].equals("write") && off[1].equals("write") ){

throw new LockException(new Exception("Record has be locked."));

}else if(in[3].equals("RC") && in[1].equals("write")){

throw new LockException(new Exception("Record has be locked."));

}else if(in[3].equals("NR")){

if(in[1].equals("write"))

throw new LockException(new Exception("Record has be locked."));

else

if(off[1].equals("write")) throw new LockException(new

Exception("Record has be locked."));

}else if(in[3].equals("SL")){

throw new LockException(new Exception("Record has be locked."));

}

}

/*

* array[0] is id

* array[1] is operation

* array[2] is ownID

* array[3] is isolate level

*/

private boolean hasPrivilege(String[] in, String[] off) {

if( (in[0].equals("*") || in[0].equals(off[0]))){

if(in[1].equals("write"))

return true;

else

if(off[1].equals("read"))

32

基于Zookeeper的锁应用开发手册

return true;

}

return false;

}

private String createPath(String group, String table){

try{

if((root, false)==null){

(root, new byte[0], _ACL_UNSAFE,

TENT);

}

if((root+"/"+group, false)==null){

(root+"/"+group, new byte[0], _ACL_UNSAFE,

TENT);

}

if((root+"/"+group+"/"+table, false)==null){

(root+"/"+group+"/"+table, new byte[0], _ACL_UNSAFE,

TENT);

}

} catch (KeeperException e) {

} catch (InterruptedException e) {

}

return root+"/"+group+"/"+table;

}

private void connectZooKeeper() throws LockException {

try {

if(zk==null) zk = new ZooKeeper(serverAddress, timeout, null);

} catch (IOException e) {

throw new LockException(e);

}

}

private void closeZookeeper(){

if(zk!=null)

try {

();

} catch (InterruptedException e) {

33

基于Zookeeper的锁应用开发手册

}

}

}finally{

zk = null;

}

@Override

synchronized public void release() throws LockException {

if(step!=1)

throw new LockException(new Exception("This lock is invalid."));

else

step = 2;

closeZookeeper();

connectZooKeeper();

String group = "";

for(String path : paths)

try {

if(!("/"+("/")[1]+"/"+("/")[2])) {

if(!("")) (group, -1);

group = "/"+("/")[1]+"/"+("/")[2];

}

Stat stat = (path, null);

if(stat!=null && Children()==0) (path, -1);

} catch (InterruptedException e) {

} catch (KeeperException e) {

}

if(!(""))

try {

(group, -1);

} catch (InterruptedException e) {

} catch (KeeperException e) {

}

closeZookeeper();

}

34

基于Zookeeper的锁应用开发手册

//(c) Copyright Beyond PAAS contributors and others 2013

package ;

/**

* LockException class.

* @author su xiaohui

* @CreateDate 2013-10-18*

*/

public class LockException extends Exception {

}

/**

*

*/

private static final long serialVersionUID = 1L;

private Exception ex;

public LockException(Exception ex){

}

public void printStackTrace() {

}

tackTrace();

= ex;

35

基于Zookeeper的锁应用开发手册

7 参考资料

 Zookeeper3.4.5官方开发文档

 Zookeeper3.4.5 官方API文档

36


本文标签: 代码 服务 线程 使用 开发