redis Distributed Lock resolve duplicate cluster implementation schedule

redis Distributed Lock resolve duplicate cluster implementation schedule

   点关注不迷路,欢迎再访!		

Scenarios

Deployment of multiple applications in the cluster, repeat the task will be a problem, in order to avoid the problem of resource waste and dirty appearance, with redis solved distributed lock

Distributed Lock achieve redis

In fact, very simple based distributed lock Redis achieve, is to use the bottom of setnx redis instructions to implement the lock, we take a look at the official definition of setnx:
SETNX key value
to the key value to value, if and only if the key does not exist.
If a given key already exists, SETNX do nothing.

Deadlock

Since setnx so powerful, need to consider some extreme scenarios.
For example, if a machine goes down suddenly in the operating state is not set to automatically lock expiration time can not release the lock, then another application would have been considered a distributed lock machine occupies mission, this time actually is not performed, and lead to deadlock.

Deadlock Problem Solution

Here we give a distributed lock set an expiration time, can automatically lock release distributed after the start of mission

Specific implementation code

/**
 * @author ex_sunqi
 * 分布式锁控制schedule
 */
@Component
@Configuration
@EnableScheduling
public class fileScheduleTask {
	    
	private final Log logger = LogFactory.getLog(getClass());	  
	private static final String LOCK = "job-lock";
    private static final String KEY = "fileTasklock";
    //单位为秒  默认10分钟
    private long redis_time = 60 * 10;

	    @Scheduled(cron = "0 0/30 * * * ?")
	    public void fileConvertJob() {
	        boolean lock = false;
	        try {
	            lock = redisTemplate.opsForValue().setIfAbsent(KEY, LOCK);
	            logger.info("是否获取到锁:" + lock);
	            if (lock) {
	            	//设置分布式锁的过期时间
                    redisTemplate.expire(KEY, redis_time , TimeUnit.SECONDS);
	            	//代码核心逻辑  
	            	      		
	            } else {
	                logger.info("没有获取到锁,不执行任务!");
	                return;
	            }
	        } finally {
	            if (lock) {
	                redisTemplate.delete(KEY);
	                logger.info("任务结束,释放锁!");
	            } else {
	                logger.info("没有获取到锁,无需释放锁!");
	            }
	        }

	    }
}

Published 101 original articles · won praise 33 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_39443053/article/details/103542774