< dependency>
< groupId> com.101tec</ groupId>
< artifactId> zkclient</ artifactId>
< version> 0.8</ version>
</ dependency>
public class OrderNumGenerateUtil
{
private static int number = 0 ;
public String getOrderNumber ( )
{
return "" + ( ++ number) ;
}
}
public class OrderService {
OrderNumGenerateUtil orderNumGenerateUtil = new OrderNumGenerateUtil ( ) ;
ZkLock zkLock = new ZkDistributedLock ( ) ;
public void getOrderNumber ( ) {
zkLock. lock ( ) ;
try {
System. out. println ( "订单编号 : \t" + orderNumGenerateUtil. getOrderNumber ( ) ) ;
} finally {
zkLock. unlock ( ) ;
}
}
public static void main ( String[ ] args) {
for ( int i = 1 ; i <= 20 ; i++ ) {
new Thread ( ( ) - > {
new OrderService ( ) . getOrderNumber ( ) ;
} , String. valueOf ( i) ) . start ( ) ;
}
}
}
public class ZkDistributedLock extends ZKAbstractTemplateLock {
public boolean tryLock ( ) {
try {
zkClient. createEphemeral ( path) ;
return true ;
} catch ( Exception e) {
return false ;
}
}
public void waitLock ( ) {
IZkDataListener iZkDataListener = new IZkDataListener ( ) {
public void handleDataChange ( String s, Object o) throws Exception {
}
public void handleDataDeleted ( String s) throws Exception {
if ( countDownLatch!= null) {
countDownLatch. countDown ( ) ;
}
}
} ;
zkClient. subscribeDataChanges ( path, iZkDataListener) ;
if ( zkClient. exists ( path) ) {
countDownLatch = new CountDownLatch ( 1 ) ;
try {
countDownLatch. await ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
zkClient. unsubscribeDataChanges ( path, iZkDataListener) ;
}
public abstract class ZkAbstractTemplateLock implements ZkLock {
public final static String ZKSERVER = "192.168.43.166:2181" ;
public static final int TIME_OUT = 1 * 1000 ;
ZkClient zkClient = new ZkClient ( ZKSERVER, TIME_OUT) ;
protected String path = "/myZkLock" ;
protected CountDownLatch countDownLatch = null;
@Override
public void lock ( ) {
if ( tryLock ( ) ) {
System. out. println ( Thread. currentThread ( ) . getName ( ) + "\t 抢占锁成功" ) ;
} else {
waitLock ( ) ;
lock ( ) ;
}
}
public abstract boolean tryLock ( ) ;
public abstract void waitLock ( ) ;
@Override
public void unlock ( ) {
if ( zkClient!= null) {
zkClient. close ( ) ;
}
System. out. println ( Thread. currentThread ( ) . getName ( ) + "\t 释放锁成功" ) ;
System. out. println ( ) ;
System. out. println ( ) ;
}
}
public interface ZkLock {
public void lock ( ) ;
public void unlock ( ) ;
}