zoukankan      html  css  js  c++  java
  • 分布式锁-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+"";
        }
    }
  • 相关阅读:
    codeforces 57C 思维
    FOJ 2232 匈牙利算法找二分图最大匹配
    UVA 101 vector
    POJ 3070 矩阵mob
    codeforces 60B bfs
    codeforces 54A
    codeforces 466C 计数 codeforces 483B 二分 容斥
    FOJ 2213 简单几何
    CCF-最优配餐(BFS)
    杂论-FTP
  • 原文地址:https://www.cnblogs.com/songfahzun/p/13051273.html
Copyright © 2011-2022 走看看