dengzedong
2025-02-21 4f7aada68f0cb506a49d4dabe302fcad952353a6
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package com.iailab.module.data.channel.http.collector.asdb;
 
import com.alibaba.fastjson.JSON;
import com.iailab.framework.common.constant.CommonConstant;
import com.iailab.framework.common.util.http.HttpUtils;
import com.iailab.module.data.channel.http.collector.asdb.vo.HttpAsdbRespDataVO;
import com.iailab.module.data.channel.http.entity.HttpApiEntity;
import com.iailab.module.data.channel.http.service.HttpApiService;
import com.iailab.module.data.common.enums.DataSourceType;
import com.iailab.module.data.common.utils.TagUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
 
/**
 * AnSteelDB采集
 *
 * @author Jay
 */
@Slf4j
@Component
public class HttpCollectorForAsdb {
    private static Map<String, HttpApiEntity> apiMap = new HashMap<>();
 
    @Autowired
    private HttpApiService httpApiService;
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(18, 36, 30, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(36), new ThreadPoolExecutor.AbortPolicy());
 
    private static final String STA_TRUE = "true";
 
    private static final int GROUP_MAX_COUNT = 300;
 
    private static final int MAX_WAIT = 30;
 
    private static final String pattern = "yyyyMMddHHmm00";
 
    private static final String IS_SUCCESS = "isSuccess";
 
    /**
     * tagName
     */
    private static final String N = "n";
 
    /**
     * dimension
     */
    private static final String D = "d";
 
    /**
     * 类型
     */
    private static final String P = "p";
 
    /**
     * dataValue
     */
    private static final String V = "v";
 
    /**
     * dataTime
     */
    private static final String T = "t";
 
    /**
     * 数据质量G:good,B:bad
     */
    private static final String Q = "q";
 
    private HttpApiEntity getHttpApi(String id) {
        if (apiMap.containsKey(id)) {
            return apiMap.get(id);
        }
        HttpApiEntity httpApi = httpApiService.info(id);
        apiMap.put(id, httpApi);
        return httpApi;
    }
 
    public BigDecimal getTagValue(String sourceId, String tagNo, Integer dimension, String valueType) {
        BigDecimal value = CommonConstant.BAD_VALUE;
        HttpApiEntity httpApi = this.getHttpApi(sourceId);
        String responseStr = HttpUtils.sendGet(httpApi.getUrl(), null, "");
        if (responseStr == null) {
            return value;
        }
        List<HttpAsdbRespDataVO> dataList = JSON.parseArray(responseStr, HttpAsdbRespDataVO.class);
        value = Objects.requireNonNull(dataList.stream().filter(data -> tagNo.equals(data.getPoint())).findFirst().orElse(null)).getValue();
        return value;
    }
 
    public Map<String, Object> getLastValues(String sourceId, List<String> tagNames) {
        Map<String, Object> result = new HashMap<>();
        HttpApiEntity httpApi = this.getHttpApi(sourceId);
        try {
            if (CollectionUtils.isEmpty(tagNames)) {
                return result;
            }
            List<String> noCacheTagNames = new ArrayList<>();//未缓存的tag
            for (int i = 0; i < tagNames.size(); i++) {
                //先查缓存
                BoundHashOperations<String, String, Object> ops = redisTemplate.boundHashOps(tagNames.get(i));
                if (ops.get(V) != null) {
                    BigDecimal value = new BigDecimal(ops.get(V).toString());
                    result.put(tagNames.get(i), value.setScale(3, RoundingMode.HALF_UP));
                } else {
                    noCacheTagNames.add(tagNames.get(i));
                }
            }
            if (CollectionUtils.isEmpty(noCacheTagNames)) {
                log.info("全部读取缓存");
                return result;
            }
            log.info("查询未缓存的数据");
            String responseStr =  HttpUtils.sendGet(httpApi.getUrl(), null, "");
            List<HttpAsdbRespDataVO> dataList = JSON.parseArray(responseStr, HttpAsdbRespDataVO.class);
            List<HttpAsdbRespDataVO> noCacheDataList = dataList.stream().filter(data -> noCacheTagNames.contains(data.getPoint())).collect(Collectors.toList());
            for (HttpAsdbRespDataVO data : noCacheDataList ){
                if (data.getValue() != null){
                    //存缓存
                    BoundHashOperations<String, String, Object> ops = redisTemplate.boundHashOps(data.getValue().toString());
                    ops.put(V, data.getValue().toString());
                    //设置过期时间
                    redisTemplate.expire(data.getValue().toString(), 10, TimeUnit.SECONDS);
                    //把查询到的数据插入结果集
                    BigDecimal value = new BigDecimal(data.getValue().toString());
                    result.put(data.getPoint(), value.setScale(3, RoundingMode.HALF_UP));
                } else {
                    result.put(data.getPoint(), CommonConstant.BAD_VALUE);
                }
            }
        } catch (Exception ex) {
            log.info("getCurrentValue异常");
            ex.printStackTrace();
            throw ex;
        }
        return result;
    }
 
    public Map<String, Object> getTagValues(List<Object[]> params, Date collectTime) {
        Map<String, Object> result = new HashMap<>();
        if (CollectionUtils.isEmpty(params)) {
            return new HashMap<>();
        }
        try {
            Map<Integer, List<Object[]>> measurePointsCountGroup = new HashMap<>();
            int pointListSize = params.size();
            int groupCount = pointListSize / GROUP_MAX_COUNT + ((pointListSize % GROUP_MAX_COUNT) > 0 ? 1 : 0);
            log.info("groupCount=" + groupCount);
            for (int i = 0; i < groupCount; i++) {
                int end = (i + 1) * GROUP_MAX_COUNT;
                if (end > pointListSize) {
                    end = pointListSize;
                }
                measurePointsCountGroup.put(i, params.subList(i * GROUP_MAX_COUNT, end));
            }
            log.info("measurePointsCountGroup.size()=" + measurePointsCountGroup.size());
            result = new ConcurrentHashMap<>(params.size());
            CountDownLatch countDownLatch = new CountDownLatch(measurePointsCountGroup.size());
            for (Map.Entry<Integer, List<Object[]>> measurePointsItem : measurePointsCountGroup.entrySet()) {
                HttpApiEntity httpApi = this.getHttpApi(measurePointsItem.getValue().get(0)[0].toString());
                // 并发
                Thread.sleep(1000);
                threadPool.submit(new Task(httpApi.getUrl(), httpApi.getCode(), result, measurePointsItem.getValue(),
                        collectTime, countDownLatch));
                // 顺序
                //this.getByHtp(result, measurePointsItem.getValue(), collectTime);
            }
            countDownLatch.await(MAX_WAIT, TimeUnit.SECONDS);
 
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
 
    /**
     * 异步采集任务
     */
    private class Task implements Runnable {
        String url;
        String sourceName;
        Date collectTime;
        Map<String, Object> result;
        List<Object[]> params;
        CountDownLatch countDownLatch;
 
        public Task(String url, String sourceName, Map<String, Object> result, List<Object[]> params,
                    Date collectTime, CountDownLatch countDownLatch) {
            this.url = url;
            this.sourceName = sourceName;
            this.result = result;
            this.collectTime = collectTime;
            this.params = params;
            this.countDownLatch = countDownLatch;
        }
 
        @Override
        public void run() {
            try {
                log.info("请求的Tag数量:" + params.size());
                this.getByHtp(url, sourceName, result, params, collectTime);
                log.info("请求结束:url=" + url);
            } catch (Exception ex) {
                log.info("获取采集值失败," + ex.getMessage());
                ex.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }
 
        /**
         * getTagDataByHttp
         *
         * @param url
         * @param sourceName
         * @param result
         * @param params
         * @param collectTime
         */
        private void getByHtp(String url, String sourceName, Map<String, Object> result, List<Object[]> params, Date collectTime) {
            String responseStr =  HttpUtils.sendGet(url, null, "");
            List<HttpAsdbRespDataVO> dataList = JSON.parseArray(responseStr, HttpAsdbRespDataVO.class);
            for (HttpAsdbRespDataVO data : dataList){
                result.put(TagUtils.genTagId(DataSourceType.HTTP.getCode(), sourceName, data.getPoint()), data.getValue());
            }
        }
    }
 
    private void getByHtp(String url, String sourceName, Map<String, Object> result, List<Object[]> params, Date collectTime) {String responseStr =  HttpUtils.sendGet(url, null, "");
        List<HttpAsdbRespDataVO> dataList = JSON.parseArray(responseStr, HttpAsdbRespDataVO.class);
        for (HttpAsdbRespDataVO data : dataList){
            result.put(TagUtils.genTagId(DataSourceType.HTTP.getCode(), sourceName, data.getPoint()), data.getValue());
        }}
}