分布式锁-redisson

pom

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.redisson/redisson-spring-boot-starter -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.13.0</version>
        </dependency>

yml

spring:
  redis:
    host: 192.168.186.134
    port: 6379
    database: 0

 

测试

@RestController
public class Hi {

    public static int v = 100;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;


    @GetMapping("/hi")
    public String hi() throws InterruptedException {
        RLock lock = redissonClient.getLock("vd-cloud-shangping");
        try {
            CountDownLatch countDownLatch = new CountDownLatch(10);
            for (int i = 0; i < 10; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int j = 0; j < 10; j++) {
                            lock.lock();
                            v = v - 1;
                            try {
                                Thread.sleep(1);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if(lock.isLocked()){
                                lock.unlock();
                            }
                            if (j == 9) {
                                countDownLatch.countDown();
                            }
                        }
                    }
                }).start();
            }
            countDownLatch.await();
            System.out.println("结束");
            System.out.println("v = " + v);
        } catch (Exception e) {
            System.out.println("异常!");
        }
        return v+"";
    }
}

 

posted @ 2020-06-05 18:16  宋发准  阅读(163)  评论(0编辑  收藏  举报