分布式锁--基于redis

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zl_1079167478/article/details/83378658

分布式锁–基于redis

上面讲锁,那么实现一个分布式锁

重点

  1. 状态—标记当前方法是否有锁
  2. 释放—释放当前方法锁

代码

/**
 * 基于redis实现分布式锁
 * 
 * @author haha
 */
@Component
public class RedisLock
{
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	public boolean lock(String key, String value)
	{
		if (stringRedisTemplate.opsForValue().setIfAbsent(key, value))
		{
			return true;
		}
		return false;
	}
	public boolean unLock(String key, String value)
	{
		String v_ = stringRedisTemplate.opsForValue().get(key);
		if (value.equals(v_))
		{
			stringRedisTemplate.opsForValue().getOperations().delete(key);// 删除key
			return true;
		}
		return false;
	}
}

讲一下,key val,key----包名+方法名(保证唯一性),val—uuid

实践

此处我使用springcloud快速搭建一个分布式的环境
eureka---- 端口8687
zuul ----端口8083
zuul-client(部署2份) —端口8080 & 8081
使用一个api来测试

@RestController
@RequestMapping("api")
public class HelloApi
{
	String classNmae = this.getClass().getName();
	@Autowired
	RedisLock redisLock;

	@GetMapping("hi")
	public Object hi() throws Exception
	{
		String methodName = Thread.currentThread().getStackTrace()[1]
				.getMethodName();
		String key = classNmae + methodName;
		String value = UUID.randomUUID().toString();
		if (redisLock.lock(key, value))
		{
			Thread.sleep(5000);
			redisLock.unLock(key, value);
			return "hi!  YOU  GET ME!";
		}
		return "i can not get lock";
	}
}

我修改了阻塞时间,方便测试,一个是5秒,一个是50秒
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zl_1079167478/article/details/83378658