大白话:各进程共用redis,每个进程都可以设置一个redis锁,但在同一时刻只能有一个进程得到锁,其他进程都要排队,等待释放锁或者锁过期自动释放,以此保证并发问题不会发生。
首先了解分布式锁之前,先了解线程锁( synchronized、lock)主要是用在方法、代码块上,能保证同一时刻只有一个线程访问,只能用在同一JVM上。
现在的系统都是分布式的,所以共享资源上,线程锁就失去了作用,所以需要分布式锁。
redis分布式锁:
满足四个条件,第一,不能发生死锁,所以要设置过期时间;第二,解铃还须系铃人,所以设置一个lockkey的value时用UUID来保证自己加的锁不被别人解锁;第三,保证同一时刻只有一个客户端获取到锁,第四,容错性,即redis集群只要部分可用,就能实现加锁解锁。
PS:
NX,是如果不存在此lockkey才加入并返回成功
PX,是时间单位毫秒(EX是秒)
示例:
package com.syc.configuration;
/**
* @author :SYC
* @date :Created in 2020/12/9 14:46
* @description:
* @modified By:
*/
import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@Component
public class RedisClient {
private static final Logger log = LoggerFactory.getLogger(RedisClient.class);
private static final Long RELEASE_SUCCESS = 1L;
@Autowired
private RedisProperties jedisProperties;
private static final String EXPIRE_SUFFIX = "-expire";
@Autowired
private JedisPool jedisPool;
public RedisClient() {
}
public boolean tryGetDistributedLock(String lockKey,String openid){
JedisPool pool = null;
Jedis jedis = null;
String result = null;
try {
pool = jedisPool;
jedis = pool.getResource();
result = jedis.set(lockKey,openid,"NX","PX",50000);
if(StrUtil.equals(result,"OK")){
return true;
}else{
return false;
}
} catch (Exception e){
e.printStackTrace();
return false;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public boolean releaseDistributedLock(String lockKey,String openid){
JedisPool pool = null;
Jedis jedis = null;
Object result = null;
try {
pool = jedisPool;
jedis = pool.getResource();
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(openid));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
} catch (Exception e){
e.printStackTrace();
return false;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
private void returnResource(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}