2021与蓝度共同重构项目,服务端
liuhaonan
2022-11-14 5cfaa9b36929545906d57c48c0f07a7c6f23d157
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.sandu.ximon.admin.utils;
 
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.context.annotation.Configuration;
 
import java.util.concurrent.TimeUnit;
 
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
 
/**
 * @author LiuHaoNan
 * @date 2022/9/6
 */
@Configuration
public class CountDownLatchUtil {
    private static Map<String, CountDownLatch> data = new HashMap<>();
 
    public void countDown(String id) {
        if (data != null && data.get(id) != null) {
            data.get(id).countDown();
        }
    }
 
    public void push(String id, CountDownLatch countDownLatch) {
        if (data != null) {
            data.put(id, countDownLatch);
        }
    }
 
    /**
     * 删除CountDown
     * @param id
     * @param countDownLatch  对象
     * @param timeout  等待时间
     */
    public void remove(String id, CountDownLatch countDownLatch, int timeout) {
        if (countDownLatch == null) {
            return;
        }
        try {
            countDownLatch.await(timeout, TimeUnit.MILLISECONDS);
            if (data != null) {
                data.remove(id);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 没有等待时间的删除
     * @param id
     */
    public void remove(String id) {
        if (data != null) {
            data.remove(id);
        }
    }
 
    public CountDownResultUtil createCoutDown(int times) {
        CountDownLatchUtil countDownLatchUtil = new CountDownLatchUtil();
        CountDownLatch countDownLatch = new CountDownLatch(times);
        //获取一个7位随机数
        String str = RandomStringUtils.randomAlphanumeric(7);
        countDownLatchUtil.push(str, countDownLatch);
        return new CountDownResultUtil(str, countDownLatch);
    }
}