简单基本的 redis 锁

 这个比较简单的实现,不过也可以用的

之后考虑用lua脚本实现

/**
 * 尝试获取简单锁
 * 这里简单的锁 不考虑并发
 * 待扩展为 单条redis执行原子锁 SETNX + EXPIRE
 * @param lockKey 锁key
 * @param expireSeconds 超期时间 秒
 * @return 是否获取成功
 */
public boolean tryGetDistributedLock(String lockKey, long expireSeconds) {
    if(StringUtils.isNotBlank(redisTemplate.opsForValue().get(lockKey))){
        return false;
    }
    redisTemplate.opsForValue().set(lockKey, "1", expireSeconds, TimeUnit.SECONDS);
    return true;
}

用法,手机发送短信锁60秒 

	/**
	 * 获得锁
	 * 锁60秒
	 *
	 * 这里之后考虑 同时进行 ip 加锁
	 * @param phone 手机号
	 * @param smsCodeTypeKey 类型key
	 * @return
	 */
	public static boolean tryGetDistributedLock(String phone, String smsCodeTypeKey){
		DataCache dataCache = (DataCache)SpringContextUtil.getBean("dataCache");
		return dataCache.tryGetDistributedLock(RedisKeyConst.CACHE_SMS_CODE_LOCK_PREFIX+smsCodeTypeKey+phone, 60);
	}

猜你喜欢

转载自blog.csdn.net/huang007guo/article/details/81183334