其他分享
首页 > 其他分享> > 关于分布式锁

关于分布式锁

作者:互联网

分布式锁

redisson

定义: redis对于java实现的分布式框架

如何使用:

  1. 引入依赖

  2.     <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson</artifactId>
        <version>3.12.5</version>
    </dependency>
    
  3. 配置redisson:1.使用程序化配置 2.使用文本配置

  4. 这里采用程序化配置

	@Bean(destroyMethod="shutdown")
	public RedissonClient redisson() {
		Config config = new Config();
		config.useSingleServer().setAddress("redis://127.0.0.1:6379");
		RedissonClient redissonClient = Redisson.create(config);
		return redissonClient;
	}

使用时直接注入即可

 @Autowired
    RedissonClient redissonClient;

可重入锁(Reetrant Lock)

公平锁

读写锁

写锁存在,读锁要等写锁释放,
读锁是一个排它锁(互斥锁),在并发写锁的情况下,写锁需要排队,读锁是一个共享锁。
写加读 读需要等写锁释放才可读
读加写 写需要等读释放才可以写

闭锁

public String lockDoor() throws InterruptedException {
		RCountDownLatch door = redissonClient.getCountDownLatch("door");
		// 设置这里有5个人
		door.trySetCount(5);
		//等待闭锁都完成
		door.await();

		return "5个人全部通过了...";
	}

	@ResponseBody
	@GetMapping("/index/go/{id}")
	public String go(@PathVariable("id") Long id) throws InterruptedException {

		RCountDownLatch door = redissonClient.getCountDownLatch("door");
		// 每访问一次相当于出去一个人
		door.countDown();
		return id + "走了";
	}

信号量测试:

public String park() throws InterruptedException {

		RSemaphore park = redissonClient.getSemaphore("park");
		//阻塞方法,获取不到信号量会一直阻塞
		park.acquire();
		//非阻塞方法,过了一定时间获取不到信号量会返回false
		boolean acquire = park.tryAcquire();
		return "获取车位 =>" + acquire;
	}

	/**
	 * 尝试获取车位
	 */
	@ResponseBody
	@GetMapping("/index/go/park")
	public String goPark() {

		RSemaphore park = redissonClient.getSemaphore("park");
		park.release();
		return "ok => 车位+1";
	}

标签:redisson,door,park,redissonClient,关于,return,public,分布式
来源: https://blog.csdn.net/isbn0123/article/details/117934442