分布式锁与锁续期
一、借助redis模版创建一个分布式锁
private boolean setRedis(String key, long expireMillis) {try {String rst = redisTemplate.execute((RedisCallback<String>) connection -> {JedisCommands commands = (JedisCommands) connection.getNativeConnection();return commands.set(key, getLockVal(key), SetParams.setParams().nx().px(expireMillis));});return StringUtils.equals(rst, "OK");} catch (Exception e) {log.error("set redis exception, key:{}", key, e);}return false;}
二、创建锁续期的方法
/*** @Author: mz* @Param: key* @Param: expireMillis 设置锁的最大持有锁时间* @Param: timeOutMillis 最大等待时间,规定100ms重试一次* @Return: boolean**/@Overridepublic boolean tryLock(String key, long expireMillis, long timeOutMillis) {boolean rst = setRedis(key, expireMillis);try {//每间隔100ms时间间隔尝试去获取一次锁(超时时间内最后一次sleep时间如果不够RETRY_INTERVAL_MILLIS,则间隔剩余时间最后尝试获取一次)while (!rst && timeOutMillis > 0) {if (timeOutMillis >= 100) {timeOutMillis = timeOutMillis - 100;TimeUnit.MILLISECONDS.sleep(100);} else {TimeUnit.MILLISECONDS.sleep(timeOutMillis);timeOutMillis = 0;}rst = setRedis(key, expireMillis);}} catch (InterruptedException e) {log.error("tryLock exception, key:{}, expireMillis:{}, timeOutMillis:{}", key, expireMillis, timeOutMillis, e);return false;}return rst;}