kimi
2020-05-27 2893347bf72477c4d108e8589a0f61e3e97a990c
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package com.highdatas.mdm.service.impl;
 
import com.highdatas.mdm.entity.*;
import com.highdatas.mdm.pojo.CodeMsg;
import com.highdatas.mdm.pojo.Page;
import com.highdatas.mdm.pojo.Result;
import com.highdatas.mdm.service.*;
import com.highdatas.mdm.util.Constant;
import com.highdatas.mdm.util.DbUtils;
import com.highdatas.mdm.util.pool.MqEntity;
import com.highdatas.mdm.util.pool.MqMessage;
import com.highdatas.mdm.util.pool.PassiveMqThreadPoolExecutor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
 
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * @author kimi
 * @description
 * @date 2020-04-14 12:58
 */
 
@Service
@Slf4j
@ConfigurationProperties(prefix = "pool")
public class DispenseServiceImpl implements DispenseService {
    @Autowired
    MasterDataService masterDataService;
    @Autowired
    IMasterAuthorService masterAuthorService;
    @Autowired
    ISysViewService viewService;
    @Autowired
    IMaintainService maintainService;
    @Autowired
    IMenuMappingService menuMappingService;
    @Autowired
    ISysDispenseLogsService dispenseLogsService;
 
    @Value("${pool.coresize}")
    private String coreSizeStr;
 
    @Value("${pool.aes}")
    private Boolean aes;
    @Value("${pool.aesurl}")
    private String aesUrl;
 
    private int coreSize;
    private Integer queueSize = 5;
    private ExecutorService priorityExecutorService;
    private volatile PriorityBlockingQueue<Runnable> priorityQueue;
    private volatile LinkedBlockingQueue infiniteQueue;
    private volatile CopyOnWriteArrayList<MqMessage> passiveRequestList;
    private  ThreadPoolExecutor infiniteExecutorService;
 
    /**
     *
     * @description:  初始化的时候创建主动,被动两个排队队列
     * @return: void
     *
     */
 
    @PostConstruct
    public void init() {
 
        if (StringUtils.isEmpty(coreSizeStr)) {
            //IO密集型 设置默认 cpu数量   预留 主动和被动两组线程池
            coreSize = Double.valueOf(Runtime.getRuntime().availableProcessors()).intValue();
        } else {
            coreSize = Integer.valueOf(coreSizeStr);
        }
        log.info("Queue_Consume_thread_size:{}",coreSize);
        this.priorityQueue = new PriorityBlockingQueue<>(queueSize);
        this.priorityExecutorService = new PassiveMqThreadPoolExecutor(coreSize, coreSize, 0L, TimeUnit.MILLISECONDS, priorityQueue);
        this.infiniteQueue = new LinkedBlockingQueue();
        this.infiniteExecutorService = new ThreadPoolExecutor(coreSize, coreSize, 0L, TimeUnit.MILLISECONDS, infiniteQueue,new ThreadPoolExecutor.AbortPolicy());
        this.passiveRequestList = new CopyOnWriteArrayList<>();
        createPassiveListenerThread();
    }
    /**
     *
     * @description:  获取是否需要
     * @return: 是否需要aes加密
     *
     */
    @Override
    public Boolean getAes() {
        return aes;
    }
    /**
     *
     * @description:  获取ars加密请求的路径
     * @return:  加密接口路径
     *
     */
    @Override
    public String getAesUrl() {
        return aesUrl;
    }
 
    /**
     *
     * @description:  创建主动分发队列
     * @return: void
     *
     */
 
    private void createPassiveListenerThread() {
        new Thread(() -> {
            log.info("被动接口准备待命。");
            while (true) {
                try{
                    if (passiveRequestList.size() == 0) {
                        Thread.sleep(5 * 1000);
                    }
                    List<MqMessage> removedList = new ArrayList<>();
                    for (MqMessage mqMessage : passiveRequestList) {
                        MqEntity mqEntity = mqMessage.getMqEntity();
                        AtomicInteger pageNo = mqEntity.getPageNo();
                        if (pageNo != null && pageNo.get() == mqEntity.getPages().get()) {
                            removedList.add(mqMessage);
                        } else {
                            MqMessage nextSubMq = createNextSubMq(mqEntity);
                            infiniteExecutorService.execute(nextSubMq);
                        }
 
                    }
                    for (MqMessage mqMessage : removedList) {
                        passiveRequestList.remove(mqMessage);
                    }
 
                }
                catch (Exception e){
                    e.printStackTrace();
                    //log
                }
            }
        }).start();
    }
 
    /**
     *
     * @description:  创建下页分发的数据包信息
     * @param  mqEntity 当前分发的entity数据
     * @return: void
     *
     */
    private MqMessage createNextSubMq(MqEntity mqEntity) {
        String type = mqEntity.getType();
        AtomicInteger pageNoAI = mqEntity.getPageNo();
        String logId = mqEntity.getLogId();
        SysDispenseLogs logs = dispenseLogsService.selectById(logId);
 
        if(pageNoAI == null) {
            String userId = mqEntity.getUserId();
            TUser user = DbUtils.getUserById(userId);
            if (user == null && logs != null) {
                logs.setErrorInfo(CodeMsg.USER_NOT_MATHED.getMsg()).updateById();
            } else if (logs != null) {
                logs.setUserName(user.getUserName());
                logs.updateById();
            }
            if (type.equalsIgnoreCase(Constant.Master)) {
                String dataId = mqEntity.getDataId();
                String tableNameByMenu = menuMappingService.getTableNameByMenu(dataId);
                Maintain maintain = maintainService.selectById(mqEntity.getMaintainId());
                MasterAuthor masterAuthor = new MasterAuthor().setTableName(tableNameByMenu);
                masterAuthor.setIncrement(mqEntity.getIncrement());
                Page initPageInfo = masterAuthorService.getInitPageInfo(masterAuthor, maintain, user, mqEntity.getIncrement());
                AtomicInteger pagesAI = new AtomicInteger(initPageInfo.getPages());
                mqEntity.setPages(pagesAI);
                mqEntity.setTotalSize(new AtomicInteger(Long.valueOf(initPageInfo.getRecordCount()).intValue()));
                AtomicInteger pageSizeAI = new AtomicInteger(initPageInfo.getPageSize());
                mqEntity.setPageSize(pageSizeAI);
                if (logs != null) {
                    SysMenu menuByTableName = menuMappingService.getMenuByTableName(maintain.getTableName());
                    if (menuByTableName != null) {
                        logs.setName(menuByTableName.getName());
                    }
                    logs.setVersion(maintain.getVersion());
                    logs.updateById();
                }
 
            } else {
                Page initPageInfo = viewService.getInitPageInfo(mqEntity.getDataId());
                AtomicInteger pagesAI = new AtomicInteger(initPageInfo.getPages());
                mqEntity.setPages(pagesAI);
                AtomicInteger pageSizeAI = new AtomicInteger(initPageInfo.getPageSize());
                mqEntity.setPageSize(pageSizeAI);
                mqEntity.setTotalSize(new AtomicInteger(Long.valueOf(initPageInfo.getRecordCount()).intValue()));
                if (logs != null) {
                    SysView sysView = viewService.selectById(mqEntity.getDataId());
                    if (sysView != null) {
                        logs.setName(sysView.getName());
                        logs.updateById();
                    }
                }
            }
            pageNoAI = new AtomicInteger();
            mqEntity.setPageNo(pageNoAI);
        }
        int i = pageNoAI.addAndGet(1);
        MqMessage mqMessage = new MqMessage(mqEntity);
        return mqMessage;
    }
    /**
     *
     * @description:  添加到主动分发队列
     * @param  message 数据包信息
     * @return: 是否添加成功
     *
     */
    @Override
    public boolean pushActiveMq(MqMessage message) {
        return pushActiveMq(message, null);
    }
    @Override
    public boolean pushActiveMq(MqMessage message, String touchType) {
        MqEntity mqEntity = message.getMqEntity();
        SysDispenseLogs preUnSuccessByMqEntity = dispenseLogsService.getPreUnSuccessByMqEntity(mqEntity);
        if (preUnSuccessByMqEntity == null) {
            SysDispenseLogs logByMqEntity = dispenseLogsService.createLogByMqEntity(mqEntity);
            if (StringUtils.isEmpty(touchType)) {
                logByMqEntity.setTouchType(touchType);
            } else {
                logByMqEntity.setTouchType("sys");
            }
 
 
            logByMqEntity.updateById();
 
            mqEntity.setLogId(logByMqEntity.getId());
 
        } else {
            mqEntity.setLogId(preUnSuccessByMqEntity.getId());
            mqEntity.setMsgKey(preUnSuccessByMqEntity.getKeyId());
            mqEntity.setPageNo(new AtomicInteger(preUnSuccessByMqEntity.getPageNo()));
            mqEntity.setPageSize(new AtomicInteger(preUnSuccessByMqEntity.getPageSize()));
            mqEntity.setPages(new AtomicInteger(preUnSuccessByMqEntity.getPages()));
        }
 
        this.passiveRequestList.add(message);
 
        return true;
    }
    /**
     *
     * @description:  添加到被动分发队列
     * @param  message 数据包信息
     * @param  touchType 触发类型
     * @param  logs 日志对象
     * @return: 是否添加成功
     *
     */
    @Override
    public Result pushPassiveMq(MqMessage message, String touchType, SysDispenseLogs logs) {
        try{
            MqMessage preMsg = null;
            if (queueSize.equals(priorityQueue.size())) {
                logs.setResult(CodeMsg.ADDQUEUE_OVER.getMsg()).updateById();
                return Result.error(CodeMsg.ADDQUEUE_OVER);
            }
            MqEntity mqEntity = message.getMqEntity();
            for (Runnable runnable : priorityQueue) {
                if (!(runnable instanceof MqMessage)) {
                    continue;
                }
                MqMessage mqMessage = (MqMessage) runnable;
                String code = mqMessage.getMqEntity().getMsgCode();
                if (StringUtils.isEmpty(code)){
                    continue;
                }
                if (code.equalsIgnoreCase(mqEntity.getMsgCode())) {
                    preMsg = (MqMessage) runnable;
                    break;
                }
            }
            if (preMsg != null) {
                int cnt = preMsg.getCnt();
                preMsg.setCnt(cnt + 1);
                logs.setResult(CodeMsg.REPEAT_ERROR.getMsg()).updateById();
                return Result.error(CodeMsg.REPEAT_ERROR);
 
            }else {
                message.setTime(new Date());
                message.setCnt(0);
            }
            priorityExecutorService.execute(message);
            SysDispenseLogs preUnSuccessByMqEntity = dispenseLogsService.getPreUnSuccessByMqEntity(mqEntity);
            if (preUnSuccessByMqEntity == null) {
               logs.setResult(CodeMsg.ADDQUEUE_SUCCESS.getMsg()).updateById();
            } else {
                mqEntity.setMsgKey(preUnSuccessByMqEntity.getKeyId());
                mqEntity.setPageNo(new AtomicInteger(preUnSuccessByMqEntity.getPageNo()));
                mqEntity.setPageSize(new AtomicInteger(preUnSuccessByMqEntity.getPageSize()));
                mqEntity.setPages(new AtomicInteger(preUnSuccessByMqEntity.getPages()));
            }
 
            return Result.success(CodeMsg.ADDQUEUE_SUCCESS);
        }catch (Exception e) {
            log.error(e.getMessage());
            logs.setErrorInfo(e.getMessage());
            return Result.success(CodeMsg.ADDQUEUE_FAIL);
        }
    }
 
    /**
     *
     * @description:  获取主动分发队列中的排队数
     * @return: 主动分发排队数
     *
     */
 
 
    @Override
    public Integer passiveQueueSize() {
        return priorityQueue.size();
    }
    /**
     *
     * @description:  获取被动分发队列中的排队数
     * @return: 被动分发排队数
     *
     */
    @Override
    public Integer avtiveQueueSize() {
        return infiniteQueue.size();
    }
 
 
}