/**
- Project Name:wklc-active-server
- File Name:SSDBLock.java
- Package Name:com.wukonglicai.active.common.util
- Date:2017-1-10 上午 10:09:59
- Copyright (c) 2017
*/
package com.wukonglicai.active.common.util;
import org.apache.log4j.Logger;
import com.wukonglicai.ssdb.api.DataStoreService;
/**
-
ClassName:SSDBLock
-
@Description :ssdb 分布式锁
-
@Date: 2017-1-10 上午 10:09:59
-
@author liuyuhui
-
@version
*/
public final class SSDBLock {private static String lockKey = "ssdb:lock";
private static int ttl = 10;private static Logger logger = Logger.getLogger(SSDBLock.class);
private SSDBLock() {
}
/**- MethodName : lock
- @Description : 锁操作,默认 key 和过期时间
- @throws Exception
- @author liuyuhui
- @date: 2017-1-10 上午 11:16:11
*/
public static void lock(DataStoreService ssdbService) {
lock(lockKey, ttl,ssdbService);
}/**
- MethodName : lock
- @Description : 锁操作,指定 key 和过期时间
- @param lockKey
- @param ttl
- @throws Exception
- @author liuyuhui
- @date: 2017-1-10 上午 11:17:33
*/
public static boolean lock(String lockKey, int ttl,DataStoreService ssdbService){
boolean flag = false;
try {
flag = getLock(lockKey, ttl, ssdbService);
while (!flag) {
Thread.sleep(30);
flag = getLock(lockKey, ttl, ssdbService);
}
} catch (Exception e) {
flag = false;
logger.error(e);
}
return flag;
}
/**
- MethodName : getLock
- @Description : 获取锁
- @param lockKey
- @param ttl
- @return
- @throws Exception
- @author liuyuhui
- @date: 2017-1-10 上午 11:17:40
*/
private static boolean getLock(String lockKey, int tt1, DataStoreService ssdbService) throws Exception {
boolean lock = false;
long result = ssdbService.getSSDBProxy().incr(lockKey, tt1);
if (result == 1) {
lock = true;
ssdbService.getSSDBProxy().expire(lockKey, ttl);
}
return lock;
}
/**
- MethodName : unlock
- @Description : 释放锁,默认 key
- @author liuyuhui
- @date: 2017-1-10 上午 11:17:52
*/
public static void unlock(DataStoreService ssdbService) {
try {
ssdbService.getSSDBProxy().del(lockKey);
} catch (Exception e) {
logger.error(e);
}
}
/**
- MethodName : unlock
- @Description : 释放锁,指定 key
- @param lockKey
- @author liuyuhui
- @date: 2017-1-10 上午 11:18:00
*/
public static void unlock(String lockKey, DataStoreService ssdbService) {
try {
ssdbService.getSSDBProxy().del(lockKey);
} catch (Exception e) {
logger.error(e);
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于