基于redis分布式并發(fā)鎖的實(shí)現(xiàn)理論原理:
https://github.com/huangz1990/redis/commit/18dbaee4f40f435970a09da427b8f45bd26b4072#diff-b643df753e12d0d07a872f91487c957dR34
主要概念:
1儒洛、如何爭(zhēng)鎖
2精耐、鎖的表達(dá)方式
3、避免死鎖
4琅锻、死鎖過(guò)期
網(wǎng)上找了一些資料:針對(duì)redisTemplate 實(shí)現(xiàn)的卦停,但是在試用過(guò)的過(guò)程中也遇到了一些坑:
public interface DistributionLock {
//加鎖成功 返回加鎖時(shí)間
Long lock(String lockKey, String threadname);
//解鎖 需要更加加鎖時(shí)間判斷是否有權(quán)限
void unlock(String lockKey, Long lockvalue, String threadname);
}
public class RedisDistributionLock implements DistributionLock{
private static final long LOCK_TIMEOUT = 10 * 1000; //加鎖超時(shí)時(shí)間 單位毫秒 意味著加鎖期間內(nèi)執(zhí)行完操作 如果未完成會(huì)有并發(fā)現(xiàn)象
private static final Logger LOG = LoggerFactory.getLogger(RedisDistributionLock.class); //redis鎖日志
@Autowired
@Qualifier("redisTemplateSerializable")
private RedisTemplate<Serializable, Serializable> redisTemplate;
//如果遇到多個(gè)RedisTemplate可以根據(jù)名字進(jìn)行注入
@Resource(name = "redisTemplateString")
private RedisTemplate<String, String> redisTemplateString;
/**
* 取到鎖加鎖 取不到鎖一直等待直到獲得鎖
*/
@Override
public synchronized Long lock(final String lockKey, String threadname) {
LOG.info(threadname + "開(kāi)始執(zhí)行加鎖");
while (true) { //循環(huán)獲取鎖
final Long lock_timeout = System.currentTimeMillis() + LOCK_TIMEOUT + 1; //鎖時(shí)間
if (redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();
byte[] value = jdkSerializer.serialize(lock_timeout);
return connection.setNX(lockKey.getBytes(), value);
}
})) { //如果加鎖成功
LOG.info(threadname + "---加鎖成功---lockKey:{},lock_timeout:{}",lockKey,lock_timeout);
redisTemplate.expire(lockKey, LOCK_TIMEOUT, TimeUnit.MILLISECONDS); //設(shè)置超時(shí)時(shí)間向胡,釋放內(nèi)存
return lock_timeout;
}else {
Long currt_lock_timeout_Str =
(Long) redisTemplate.opsForValue().get(lockKey); // redis里的時(shí)間
if (currt_lock_timeout_Str != null && currt_lock_timeout_Str < System.currentTimeMillis()) { //鎖已經(jīng)失效
// 判斷是否為空,不為空的情況下惊完,說(shuō)明已經(jīng)失效僵芹,如果被其他線程設(shè)置了值,則第二個(gè)條件判斷是無(wú)法執(zhí)行
Long old_lock_timeout_Str = (Long) redisTemplate.opsForValue().getAndSet(lockKey, lock_timeout);
// 獲取上一個(gè)鎖到期時(shí)間专执,并設(shè)置現(xiàn)在的鎖到期時(shí)間
if (old_lock_timeout_Str != null && old_lock_timeout_Str.equals(currt_lock_timeout_Str)) {
// 如過(guò)這個(gè)時(shí)候淮捆,多個(gè)線程恰好都到了這里,但是只有一個(gè)線程的設(shè)置值和當(dāng)前值相同本股,他才有權(quán)利獲取鎖
LOG.info(threadname + "---加鎖成功---lockKey:{},lock_timeout:{}",lockKey,lock_timeout);
redisTemplate.expire(lockKey, LOCK_TIMEOUT, TimeUnit.MILLISECONDS); //設(shè)置超時(shí)時(shí)間攀痊,釋放內(nèi)存
return lock_timeout;//返回加鎖時(shí)間
}
}
}
try {
LOG.info(threadname + "等待加鎖,睡眠100毫秒");
TimeUnit.MILLISECONDS.sleep(100);//睡眠100毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public synchronized void unlock(String lockKey, Long lockvalue, String threadname) {
Long currt_lock_timeout_Str = (Long) redisTemplate.opsForValue().get(lockKey); // redis里的時(shí)間
if (currt_lock_timeout_Str != null && currt_lock_timeout_Str .equals( lockvalue)) {//如果是加鎖者 則刪除鎖 如果不是則等待自動(dòng)過(guò)期 重新競(jìng)爭(zhēng)加鎖
redisTemplate.delete(lockKey); //刪除鍵
LOG.info(threadname + "解鎖成功:lockKey{},lockValue:{}",lockKey,lockvalue);
}
}
}
關(guān)鍵點(diǎn):這里的集中序列化方式一定要配置拄显,不然取不到值苟径,調(diào)試了很久
@Bean("redisTemplateSerializable")
RedisTemplate<Serializable,Serializable> redisTemplateSerializable(RedisConnectionFactory connectionFactory) {
RedisTemplate<Serializable, Serializable> template = new RedisTemplate<Serializable, Serializable>();
template.setConnectionFactory(connectionFactory);
/**
* 添加屬性
*/
StringRedisSerializer stringRedisSerializernew =new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializernew);
template.setHashKeySerializer(stringRedisSerializernew);
JdkSerializationRedisSerializer jdkSerializationRedisSerializer =new JdkSerializationRedisSerializer();
template.setValueSerializer(jdkSerializationRedisSerializer);
template.setHashValueSerializer(jdkSerializationRedisSerializer);
return template;
}
測(cè)試代碼:要注意的是:最好在外層加同步鎖,否則會(huì)出現(xiàn)一種奇怪的現(xiàn)象躬审,就是每次都是到鎖過(guò)期才釋放鎖棘街,搶先進(jìn)入任務(wù)的線程,會(huì)被堵在釋放鎖的外面:
@RequestMapping(value = {"/redis/dist/test/{lockKey}"},method = RequestMethod.GET)
public void testDistLock(@PathVariable("lockKey") String lockKey1){
AtomicBoolean isFinish = new AtomicBoolean(false);
final ReentrantLock lock = new ReentrantLock();
for(int i=0;i<1;i++){
final String lockKey = lockKey1;
new Thread(new Runnable() {
@Override
public void run() {
try {
lock.lockInterruptibly();
Long lockValue = redisDistributionLock.lock(lockKey,Thread.currentThread().getName());
System.out.println("獲得鎖:"+lockValue);
System.out.println("執(zhí)行任務(wù)......");
// redisDistributionLock.unlock(lockKey,lockValue,Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}).start();
}
}