思路
使用setnx 命令
setnx命令当key不存在时,会set进去,当已存在则返回false
set完之后使用 exprie命令对key设置过期时间
释放锁的时候主动调用del释放锁
测试代码
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Random random = new Random();
for(int i=0;i<100;i++) {
executorService.submit(()->{
try {
while(!lock("lock",60)) {
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() +"重新获取锁");
}
//处理事务
System.out.println(Thread.currentThread().getName() +"处理事务");
Thread.sleep(1000);
unLock("lock");
System.out.println(Thread.currentThread().getName() +"释放锁");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
}
executorService.shutdown();
}
public static boolean lock(String key,int seconds) {
Jedis jedis = getPoolResouce();
Long setnx = jedis.setnx(key, "");
jedis.expire(key, seconds);
jedis.close();
return setnx.longValue() > 0 ? Boolean.TRUE:Boolean.FALSE;
}
public static void unLock(String key) {
Jedis jedis = getPoolResouce();
jedis.del(key);
}