From 05fe1e20f95e4372bf0b4808b4e3e67ff6e6e2db Mon Sep 17 00:00:00 2001 From: ptlyu29vw Date: Tue, 17 May 2022 21:00:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- RedissonTest.java | 59 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 RedissonTest.java diff --git a/RedissonTest.java b/RedissonTest.java new file mode 100644 index 0000000..e72417c --- /dev/null +++ b/RedissonTest.java @@ -0,0 +1,59 @@ +package com.hmdp; + +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.redisson.api.RLock; +import org.redisson.api.RedissonClient; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; +import java.util.concurrent.TimeUnit; + +@Slf4j +@SpringBootTest +class RedissonTest { + + @Resource + private RedissonClient redissonClient; + + private RLock lock; + + @BeforeEach + void setUp() { + lock = redissonClient.getLock("order"); + } + + @Test + void method1() throws InterruptedException { + // 尝试获取锁 + boolean isLock = lock.tryLock(1L, TimeUnit.SECONDS); + if (!isLock) { + log.error("获取锁失败 .... 1"); + return; + } + try { + log.info("获取锁成功 .... 1"); + method2(); + log.info("开始执行业务 ... 1"); + } finally { + log.warn("准备释放锁 .... 1"); + lock.unlock(); + } + } + void method2() { + // 尝试获取锁 + boolean isLock = lock.tryLock(); + if (!isLock) { + log.error("获取锁失败 .... 2"); + return; + } + try { + log.info("获取锁成功 .... 2"); + log.info("开始执行业务 ... 2"); + } finally { + log.warn("准备释放锁 .... 2"); + lock.unlock(); + } + } +}