import redis.clients.jedis.Jedis;
//java代码模拟处理redis分布式锁代码
public class redisTest {
private static long timeout = 1000;
public static void main(String[] args) throws Exception {
new Thread(new Runnable(){
@Override
public void run() {
long sid = 0;
try {
sid = getSetId("subThread");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("sid="+sid);
}}).start();
long mid=getSetId("mainThread");
System.out.println("mid="+mid);
}
public static long getSetId(String thread) throws Exception {
Long id = null;
while (true) {
boolean success = getLock("id_lock");
if (success) {
Jedis jedis = new Jedis("192.168.6.20", 6385);
jedis.auth("QvXtTZN4MyBDknj5");
String strId=jedis.get("id");
// 如果id为空说明未设置id值
if (strId==null||strId=="") {
id = 100000001l;
} else {
id=Long.valueOf(strId);
id = id + 1;
}
jedis.set("id", String.valueOf(id));
// 释放锁
releaseLock("id_lock");
break;
} else {
System.out.println("thread="+thread+",锁在使用中");
Thread.sleep(100);
}
}
return id;
}
public static boolean getLock(String lockKey) {
boolean success = false; // 默认获取锁失败
long value = System.currentTimeMillis() + timeout; // 设置锁值
// SETNX lockKey 成功
Jedis jedis = new Jedis("192.168.6.20", 6385);
jedis.auth("QvXtTZN4MyBDknj5");
long isExit = jedis.setnx(lockKey, String.valueOf(value));
// isExit=1 说明SETNX成功,成功获取一个锁
if (isExit == 1)
success = true;
// 否则 SETNX失败,说明锁仍然被其他对象保持,检查其是否已经超时
else {
long oldValue = Long.valueOf(jedis.get(lockKey));
// 锁已经超时
if (oldValue < System.currentTimeMillis()) {
String getValue = jedis.getSet(lockKey, String.valueOf(value));
// 获取锁成功
if (Long.valueOf(getValue) == oldValue)
success = true;
// 已被其他进程捷足先登了
else
success = false;
}
// 未超时,则直接返回失败
else
success = false;
}
return success;
}
// 释放锁
public static void releaseLock(String lockKey) {
Jedis jedis = new Jedis("192.168.6.20", 6385);
jedis.auth("QvXtTZN4MyBDknj5");
long current = System.currentTimeMillis();
// 避免删除非自己获取得到的锁
if (current < Long.valueOf(jedis.get(lockKey)))
jedis.del(lockKey);
}
}