分布式锁在单元测试中的问题?

刚开始学分布式锁,在使用单元测试对redission进行测试的时候发现,在多次测试过程中锁会有获取失败的机率,想问一下原因

测试类代码如下:

package com.hmdp;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;


// 可重入锁 - 解决两个加锁功能的互相调用时的问题
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedissionTest {

    @Autowired
    public RedissonClient rc;

    public RLock rlock;



    @Before
    public void before(){
        rlock = rc.getLock("Textlock");

//        rlock = rc.getLock("name23");

        System.out.println(rlock.tryLock());
    }

    @Test
    public void test1Method(){

        System.out.println(rc);
        System.out.println(rlock);

        boolean b = rlock.tryLock();

        if (!b){
            System.out.println("获取锁1失败...");

            return;
        }

        System.out.println("获取锁1成功...");
        test2Method();
//            Thread.sleep(10);


        rlock.unlock();




    }

    @Test
    public void test2Method() {

//            boolean b = rlock.tryLock(1, 10000, TimeUnit.SECONDS);
        boolean b = rlock.tryLock();

        if (!b){
            System.out.println("获取锁2失败...");

            return ;
        }

        System.out.println("获取锁2成功...");

        rlock.unlock();



    }
}

配置类代码

package com.hmdp.utils;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.ObjectInputFilter;

@Configuration
public class RedissionConfig {
    @Bean
    public RedissonClient getRedissonClient(){
        Config c = new Config();

        c.useSingleServer().setAddress("redis://60.205.170.18:6379").setPassword("redis7");

        return Redisson.create(c);
    }
}

运行截图
image.pngimage.png

阅读 2k
1 个回答
@Before
public void before(){
    rlock = rc.getLock("Textlock");
}

@Test
public void test1Method(){
    rlock.lock();
    try {
        System.out.println("获取锁1成功...");
        test2Method();
    } finally {
        rlock.unlock();
    }
}

@Test
public void test2Method() {
    rlock.lock();
    try {
        System.out.println("获取锁2成功...");
    } finally {
        rlock.unlock();
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏