一種簡單的redis分佈式鎖方案

前言

用於分佈式程序彼此之間不能同時執行的場景。例如計算程序等。redis

代碼

鎖工具類

@Component
public class RedisLockUtil {

	@Autowired
	private RedisTemplate redisTemplate;

	private static final String CALC_LOCK_KEY = "CalculateLock";
	private static final Long CALC_LOCK_TIME = 30L;


	public boolean setIfAbsent (String key,String value,Long lockTime) {
		return redisTemplate.opsForValue().setIfAbsent(key,value,lockTime,TimeUnit.MINUTES);
	}

	public String getValue(String key) {
		return (String) redisTemplate.opsForValue().get(key);
	}

	public void delete (String key) {
		redisTemplate.delete(key);
	}

	public boolean calcLock (String value) {
		return redisTemplate.opsForValue().setIfAbsent(CALC_LOCK_KEY,value,CALC_LOCK_TIME,TimeUnit.MINUTES);
	}

	public String getCalcValue () {
		return (String) redisTemplate.opsForValue().get(CALC_LOCK_KEY);
	}

	public String getTimeSeed(){
		return String.valueOf(new Date().getTime());
	}

	public void unCalclock () {
		redisTemplate.delete(CALC_LOCK_KEY);
	}


}

實際調用的代碼

@PostMapping("/calc")
public void calc() throws Exception{

	String redisValue = "計算"+redisLockUtil.getTimeSeed();
	boolean flag = redisLockUtil.calcLock(redisValue);
	if(!flag){
		return ;
	}
	try{
		//業務代碼
	}catch (Exception e){
		e.printStackTrace();
		//業務代碼
		return ;
	}finally {
		//爲了防止過時致使刪除了其餘人的鎖
		if(redisValue.equals(redisLockUtil.getCalcValue())){
			redisLockUtil.unCalclock();
		}
	}
	return;
}
相關文章
相關標籤/搜索