分布式锁
分布式锁是一种保证安全的访问分布式机器,在单机状态是使用lock来加对于当前系统的唯一的锁,但是在分布式环境中,如果还是使用
这种方式,会导致整个机群里有多少个机器就会有几把锁,这根本就不能达到要求,而我们的要求就是整个环境就只能有一把锁,因此我们
可以把这把锁提取出来,单独管理,每一个请求过来,不管分发到那台机器上,首先就得从管理这获取锁,才能继续往下访问
redis实现锁
- setnx命令
语法:
SETNX key value
功能:
当且仅当 key 不存在,将 key 的值设为 value ,并返回1;若给定的 key 已经存在,则 SETNX 不做任何动作,并返回0。 - expire命令
语法:
SETNX key value
功能:
为key设置存活时间,用来保证发生死锁的情况下放弃锁 - DEL命令
语法:
DEL key [KEY …]
功能:
删除给定的一个或多个 key ,不存在的 key 会被忽略。
代码实现
实现锁
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisException;
import java.util.List;
import java.util.UUID;
public class DistributedLock {
private JedisPool jedisPool;
DistributedLock(JedisPool jedisPool){
this.jedisPool = jedisPool;
}
public String lockWithTimeout(String locaName,long acquireTimeout, long timeout) {
Jedis conn = null;
String retIdentifier = null;
try {
// 获取连接
conn = jedisPool.getResource();
// 随机生成一个value
String identifier = UUID.randomUUID().toString();
// 锁名,即key值
String lockKey = "lock:" + locaName;
// 超时时间,上锁后超过此时间则自动释放锁
int lockExpire = (int)(timeout / 1000);
// 获取锁的超时时间,超过这个时间则放弃获取锁
long end = System.currentTimeMillis() + acquireTimeout;
while (System.currentTimeMillis() < end) {
if (conn.setnx(lockKey, identifier) == 1) {
conn.expire(lockKey, lockExpire);
// 返回value值,用于释放锁时间确认
retIdentifier = identifier;
return retIdentifier;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} catch (JedisException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
return null;
}
public boolean releaseLock(String lockName, String identifier) {
Jedis conn = null;
String lockKey = "lock:" + lockName;
boolean retFlag = false;
try {
conn = jedisPool.getResource();
while (true) {
// 监视lock,准备开始事务
conn.watch(lockKey);
// 通过前面返回的value值判断是不是该锁,若是该锁,则删除,释放锁
if (identifier.equals(conn.get(lockKey))) {
Transaction transaction = conn.multi();
transaction.del(lockKey);
List<Object> results = transaction.exec();
if (results == null) {
continue;
}
retFlag = true;
}
conn.unwatch();
break;
}
} catch (JedisException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
return retFlag;
}
}
测试
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(500, 5000, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
Service ser = new Service();
for (int i = 0; i < 50; i++) {
tpe.execute(ser);
}
}
}
class Service implements Runnable {
private static JedisPool pool = null;
static {
JedisPoolConfig config = new JedisPoolConfig();
// 设置最大连接数
config.setMaxTotal(200);
// 设置最大空闲数
config.setMaxIdle(8);
// 设置最大等待时间
config.setMaxWaitMillis(1000 * 100);
// 在borrow一个jedis实例时,是否需要验证,若为true,则所有jedis实例均是可用的
config.setTestOnBorrow(true);
pool = new JedisPool(config, "127.0.0.1", 6379, 3000);
}
DistributedLock distributedLock = new DistributedLock(pool);
int n = 50;
@Override
public void run() {
label:
while (true) {
if(n==0){
System.out.println(Thread.currentThread().getName() +"结束");
break label;
}
String lock = distributedLock.lockWithTimeout(Thread.currentThread().getName(), 5000, 1000);
if (lock != null) {
System.out.println(Thread.currentThread().getName() + ":获得了锁");
if(n==0){
System.out.println(Thread.currentThread().getName() +"结束");
break label;
}
System.out.println(--n);
distributedLock.releaseLock(Thread.currentThread().getName(), lock);
} else {
System.out.println(Thread.currentThread().getName() + ":获取锁超时");
}
}
}
}
结果
pool-1-thread-27:获得了锁
8
pool-1-thread-27:获得了锁
7
pool-1-thread-27:获得了锁
6
pool-1-thread-27:获得了锁
5
pool-1-thread-27:获得了锁
4
pool-1-thread-27:获得了锁
3
pool-1-thread-27:获得了锁
2
pool-1-thread-27:获得了锁
1
pool-1-thread-2:获得了锁
0
pool-1-thread-27:获得了锁
pool-1-thread-27结束
pool-1-thread-48结束
可以看出,在多线程环境下,每个线程都必须从redis那里获取到锁,才能操作,否则就阻塞,直到获取到锁,或者阻塞时间过长退出获取锁