Home > Database > Redis > body text

Will redis cause deadlock problems?

Release: 2019-07-08 09:14:05
Original
5558 people have browsed it

Will redis cause deadlock problems?

As far as distributed locks are concerned, a common problem is that if a service setnx is successful, but if there is a downtime or some special factors during unlocking, it cannot be unlocked. Then other services will fall into a deadlock state. Therefore, while using setnx, we want to use the expire instruction to perform an expiration operation on the lock. From the instructions, we can see that the setnx and expire instructions are separate. If there are special factors during the gap in the process, the instruction cannot continue. , will also lead to deadlock.

Solution:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
 
@Component
public class RedisLock {
 
    Logger logger = LoggerFactory.getLogger(this.getClass());
 
    @Autowired
    private StringRedisTemplate redisTemplate;
 
    /**
     * 加锁
     * @param key   
     * @param value 当前时间 + 超时时间
     * @return
     */
    public boolean lock(String key, String value) {
    
        if (redisTemplate.opsForValue().setIfAbsent(key, value)) {     
            // 这个其实就是setnx命令,只不过在java这边稍有变化,返回的是boolean
            // 设置个过期时间,当然如果在这中间的空隙过程中如果有特殊因素导致指令无法继续,也会导致死锁的产生,如果死锁出现,则后续代码会处理
            redisTemplate.expire(key, lockTime, TimeUnit.SECONDS);
            return true;
        }
 
        // 避免死锁,且只让一个线程拿到锁
        String currentValue = redisTemplate.opsForValue().get(key);
        // 如果锁过期了
        if (!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue) < System.currentTimeMillis()) {
            //获取上一个锁的时间
            String oldValues = redisTemplate.opsForValue().getAndSet(key, value);
 
            /*
               只会让一个线程拿到锁
               如果旧的value和currentValue相等,只会有一个线程达成条件,因为第二个线程拿到的oldValue已经和currentValue不一样了
             */
            if (!StringUtils.isEmpty(oldValues) && oldValues.equals(currentValue)) {
                return true;
            }
        }
        return false;
    }
 
 
    /**
     * 解锁
     * @param key
     * @param value
     */
    public void unlock(String key, String value) {
        try {
            String currentValue = redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
                redisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            logger.error("redis分布式锁解锁异常,{}", e);
        }
    }
}
Copy after login

Call:

 //加锁
    long time = System.currentTimeMillis() + 1000 * lockTime //超时时间:10秒,最好设为常量
 
    boolean isLock = redisLock.lock(...keyName, String.valueOf(time));
    if(!isLock){
        throw new RuntimeException("系统正忙");
    }
    
    // doSomething...
    
    
    //解锁
    redisLock.unlock(...keyName, String.valueOf(time));
Copy after login

For more Redis related knowledge, please visit the Redis usage tutorial column!

The above is the detailed content of Will redis cause deadlock problems?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template