MessageBusProcessor.java
24.5 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package com.tianbo.messagebus.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tianbo.messagebus.controller.response.ResultJson;
import com.tianbo.messagebus.model.*;
import com.tianbo.messagebus.myinterface.KafkaReciveApi;
import com.tianbo.messagebus.myinterface.KafkaSendApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
@Service
//@EnableAsync
@Slf4j
public class MessageBusProcessor {
/**http://10.161.4.20:8083/
* 账户登录地址
*/
@Value("${message-bus.url.login-url}")
private String LOGIN_URL;
/**
* 账号名
*/
@Value("${message-bus.auth.username}")
private String USER_NAME;
// private static final String USER_NAME = "HYYW";
/**
* 登陆密码
*/
@Value("${message-bus.auth.password}")
private String USER_PASS;
// private static final String USER_PASS = "ZZecargo123";
/**
* 心跳接口地址
*/
@Value("${message-bus.url.hearbit-url}")
private String HEARTBEAT_URL;
/**
* 心跳间隔时间 单位S
*/
@Value("${message-bus.heartbit-interval}")
private int HEARTBIT_INTERVAL;
/**
* 发送报文地址
*/
@Value("${message-bus.url.send-url}")
private String SEND_MSG_URL;
/**
* 接收报文地址
*/
@Value("${message-bus.url.get-url}")
private String GET_MSG_URL;
/**
* 存储登录后的token
*/
private static String TOKEN = "";
/**
* 登录成功状态
*/
private static Boolean LOGIN_STATUS=false;
/**
* 失败重发请求次数
*/
private static final int RETRY_TIMES= 100;
/**
* HTTP请求框架
*/
@Resource
private RestTemplate restTemplate;
@Autowired
KafkaReciveApi kafkaReciveApi;
@Autowired
KafkaSendApi kafkaSendApi;
@Autowired
Custom_Response_Service custom_response_service;
/**
* 发起登录,存储token
*
* @return
*/
public Boolean login() {
try {
/*
* 发起HTTP 登录请求
* 登录接口的请求头为application/x-www-form-urlencoded
*/
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
/*
* 请求参数
*/
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", USER_NAME);
params.add("password", USER_PASS);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
/*
* 提交HTTP访问,获取返回信息
*/
ResponseEntity<String> response = restTemplate.postForEntity(LOGIN_URL, request, String.class);
// 输出结果
log.info(response.getBody());
/*
校验是否登录成功
*/
if (response.getStatusCode().equals(HttpStatus.OK)) {
/**
* 从返回信息中确定是否登录成功,并取得token
* 返回格式
* {
"code":200,
"data":{
"account":"yangyucheng",
"token":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2MCIsIm5hbWUiOiLmnajnjonmiJDmtYvor5UiLCJpZCI6NjAsImlhdCI6MTYxNzM0ODM3MiwiYWNjb3VudCI6Inlhbmd5dWNoZW5nIn0.ElAs7BtV1tu6ApQXuPXzgXUgvja76bjEb-zxqhUON48"
},
"message":"success",
"success":true,
"time":20210402152612604
}
*/
JSONObject resJson = JSON.parseObject(response.getBody());
JSONObject resData = resJson.getJSONObject("data");
String resCode = resJson.getString("code");
/*
校验并获取登陆成功后返回的token
*/
String authToken = resData.getString("token");
if ("200".equals(resCode) && !StringUtils.isEmpty(authToken) && authToken.length() > 10) {
LOGIN_STATUS = true;
//设置请求头部Authorization为token, token的类型为Bearer
TOKEN = authToken;
/*
登录成功开始心跳
*/
// startHeartBit();
log.info("登录成功");
return true;
}else {
log.error("登录失败");
return false;
}
} else {
log.error("登录失败");
return false;
}
} catch (Exception e) {
log.error("登录失败->{}",e.toString());
return false;
}
}
/**
* 定时心跳,维持在线状态,每10秒访问一次心跳接口
*/
public void startHeartBit() {
try {
while (true) {
heartBit();
Thread.sleep(HEARTBIT_INTERVAL);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 获取返回信息的状态码
* @param response response对象
* @return
*/
private String getResponseDataCode(ResponseEntity<String> response){
JSONObject resJson = JSON.parseObject(response.getBody());
String code = resJson.getString("code");
return code;
}
// @Scheduled(fixedDelay = 10000)
public void heartBit() {
if (!StringUtils.isEmpty(TOKEN) && LOGIN_STATUS){
/*
* 发起HTTP 登录请求
* 登录接口的请求头为application/x-www-form-urlencoded
*/
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
/*
* 设置获取到的token到头部信息Authorization节点中
*/
headers.setBearerAuth(TOKEN);
/*
* 心跳接口无参数,访问接口即可
*/
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
/*
* 提交HTTP访问,获取返回信息
*/
ResponseEntity<String> response = restTemplate.postForEntity(HEARTBEAT_URL, request, String.class);
// 输出结果
log.info(response.getBody());
if (response.getStatusCode().equals(HttpStatus.OK)) {
log.info("心跳成功,token:[{}]",TOKEN);
} else {
log.error("心跳失败");
}
}
}
/**
* 发送消息
*
* @return
*/
public Boolean sendMsg(MSG msg) {
if (LOGIN_STATUS) {
try{
log.info("………………开始发送消息:{}………………",msg.toString());
/*
* 发起HTTP 登录请求
* 登录接口的请求头为application/json
*/
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
MSGS msgs = new MSGS();
msg.getHEADER().setSNDR("HYYW");
msgs.setMSG(msg);
/*
设置要发送的实体类并将实体转换成Json字符串,这里以MAP类型举例
*/
// Map<String, String> dataModel = new HashMap<>();
// dataModel.put("flightNo", "CV987");
// dataModel.put("flightDate", "MAY01");
// dataModel.put("waybillNo", "172-12345678");
// dataModel.put("weight", "20.01");
// dataModel.put("piece", "2");
// msg.getMSG().setBODY(JSON.toJSONString(dataModel));
/*
* 设置获取到的token到头部信息Authorization节点中
*/
headers.setBearerAuth(TOKEN);
/*
* 发起消息接口访问,发送消息
*/
HttpEntity<MSGS> request = new HttpEntity<MSGS>(msgs, headers);
ResponseEntity<String> response = restTemplate.postForEntity(SEND_MSG_URL, request, String.class);
if (response.getStatusCode().equals(HttpStatus.OK)) {
JSONObject resJson = JSON.parseObject(response.getBody());
String code = resJson.getString("code");
if ("200".equals(code)) {
log.info("………………消息发送成功………………");
return true;
}
}
log.info("消息发送失败->{}",response.getBody());
}catch (Exception e){
log.info("消息发送失败->{},失败原因:{}",msg.toString(),e.toString());
log.error("消息发送失败->{},失败原因:{}",msg.toString(),e.toString());
return false;
}
}else {
log.info("未登陆,消息发送失败");
}
return false;
}
/**
* 收取消息
*
* @return
*/
// @Async
// @Scheduled(fixedRate = 1000)
public JSONArray getMsg() {
if(!LOGIN_STATUS){
login();
return null;
}
/*
* 发起HTTP 登录请求
* 登录接口的请求头为application/json
*/
try{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setBearerAuth(TOKEN);
/*
* 请求参数拼装
*/
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("username", "HYYW");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
/*
* 提交HTTP访问,获取返回信息
*/
ResponseEntity<String> response = restTemplate.postForEntity(GET_MSG_URL, request, String.class);
// 输出结果
log.info("接口访问结果:{}",response);
if (response.getStatusCode().equals(HttpStatus.OK)) {
/*
* 从返回信息中确定是否获取到消息
*/
JSONObject resJson = JSON.parseObject(response.getBody());
String code = resJson.getString("code");
if ("200".equals(code)){
JSONArray data = resJson.getJSONArray("data");
log.info("消息接收成功,接收消息数量>>>{}<<<",data.size());
for (int i = 0; i<data.size() ; i++) {
/*
取得是大数据小组的实体,他们的msg.body的封装是以对象实体object封装的。不是json字符串。
*/
String msg = data.getObject(i,String.class);
log.info("循环处理消息[{}]---{}---",i,msg);
JSONObject rootJson = JSON.parseObject(msg);
JSONObject msgJson = rootJson.getJSONObject("MSG");
JSONObject body = msgJson.getJSONObject("BODY");
HEADER msgHeader = msgJson.getObject("HEADER",HEADER.class);
MSG transMsg= new MSG();
String transBody = body.toJSONString();
transMsg.setHEADER(msgHeader);
transMsg.setBODY(transBody);
/*
自定义对返回数据的处理
*/
log.info("开始转发消息");
Boolean sendResult = sendMsg(transMsg);
/**
* todo:转发消息失败处理
*/
if(!sendResult){
log.error("!!!!!!消息--->{}<---转发失败!!!!!!,尝试重发",transMsg.toString());
//todo:消息备份或者重发?
reSend(transMsg);
}
}
return data;
}
} else {
log.error("消息获取失败");
return new JSONArray();
}
}catch (Exception httpE){
log.info("消息获取失败,失败原因:{}",httpE.toString());
log.error("消息获取失败,失败原因:{}",httpE.toString());
}
return new JSONArray();
}
/**
* feigin从服务直接获取消息
*/
// @Scheduled(fixedRate = 5000)
public void getDataFromFeigin(){
try{
//初始化数据库
CUSTOM_RESPONSE test = custom_response_service.selectByPrimaryKey("111");
log.info("1-开始执行获取任务,获取账号为:{}",USER_NAME);
if(!StringUtils.isEmpty(USER_NAME)){
ResultJson<List<String>> listResultJson = kafkaReciveApi.recive(USER_NAME);
log.info("2-获取结果为:{},数量为:{}",listResultJson.toString(),listResultJson.getData().size());
if ("200".equals(listResultJson.getCode()) && listResultJson.getData()!=null && listResultJson.getData().size()>0){
log.info("3-开始处理获取数据");
List<String> dataList = listResultJson.getData();
for (int i = 0; i <dataList.size() ; i++) {
String msg = dataList.get(i);
log.info("4-循环处理消息[{}]--->{}<---",i,msg);
JSONObject rootJson = JSON.parseObject(msg);
JSONObject msgJson = rootJson.getJSONObject("MSG");
//回执实体
JSONObject body = msgJson.getJSONObject("BODY");
//报头
HEADER msgHeader = msgJson.getObject("HEADER",HEADER.class);
//判断类型
if ("CDHZ".equals(msgHeader.getSTYPE())){
log.info("@[一]@消息为舱单回执");
CUSTOM_RESPONSE custom_response_nmms2 = new CUSTOM_RESPONSE();
//判断回执类型
JSONObject manifest = body.getJSONObject("Manifest");
JSONObject head = manifest.getJSONObject("Head");
if(head != null){
log.info("@[.]开始回执报头解析");
String messageType = head.getString("MessageType");
String messageID = head.getString("MessageID");
String sendTime = head.getString("SendTime");
String senderID = head.getString("SenderID");
String receiverID = head.getString("ReceiverID");
Integer version = head.getInteger("Version");
Integer functionCode = head.getInteger("FunctionCode");
log.info("@[MessageType:{}]回执报头解析完毕",messageType);
if("MT2201".equals(messageType) || "MT9999".equals(messageType) || "MT3201".equals(messageType)){
log.info("@[二]@开始解析:{}",messageType);
messageType = "MT2201";
// 航班信息
JSONObject response = manifest.getJSONObject("Response");
if (response!=null){
JSONObject borderTransportMeans = response.getJSONObject("BorderTransportMeans");
if (borderTransportMeans!=null ){
String flightNo = "UNKONW";
String flightDate = "20101010";
String journeyid = borderTransportMeans.getString("JourneyID");
//运单信息
JSONObject consignment = response.getJSONObject("Consignment");
if (consignment!=null){
JSONObject responseType = consignment.getJSONObject("ResponseType");
JSONObject transportContractDocument = consignment.getJSONObject("TransportContractDocument");
JSONObject associatedTransportDocument = consignment.getJSONObject("AssociatedTransportDocument");
Integer responseCode = 3;
String responseText = "回执报文未有信息";
if (responseType!=null){
//回执代码
responseCode = responseType.getIntValue("Code");
//回执内容
responseText = responseType.getString("Text");
}
String waybillMaster = "00000000000";
if (transportContractDocument!=null){
waybillMaster = transportContractDocument.getString("ID");
}
String waybillSecond="";
if (associatedTransportDocument!=null){
waybillSecond = associatedTransportDocument.getString("ID");
}
CustomReception customReception = new CustomReception( messageType,
flightNo,
flightDate,
waybillMaster.toString(),
waybillSecond,
responseCode.toString(),
responseText,
messageID,
sendTime,
senderID,
receiverID,
version.toString(),
functionCode.toString());
/**
* 如果回执中没有携带航班信息节点,说明是出错报文
* 到发送日志表根据messageid 找到相应的发送日志报文的航班及运单信息,再进行解析
*/
if(!org.apache.commons.lang.StringUtils.isEmpty(journeyid)){
String[] flightList = journeyid.split("/");
if(flightList.length > 0){
flightNo = flightList[0];
flightDate = flightList[1];
log.info("@[三]@航班信息为:{}",journeyid);
customReception.setFlightNo(flightNo);
customReception.setFlightDate(flightDate);
}
custom_response_nmms2 = new CUSTOM_RESPONSE(customReception);
}else {
custom_response_nmms2 = new CUSTOM_RESPONSE(customReception);
custom_response_nmms2 = custom_response_service.getWaybillInfoByCutomResponse(custom_response_nmms2);
}
log.info("[(三.一)]{{}",custom_response_nmms2);
int ii = custom_response_service.secondAnalysisReception(custom_response_nmms2);
log.info("@[四]@回执解析完毕[{}]\n@@^PARSE SUCCESS^@@",ii);
}else {
log.info("@[四零零]@回执报文没有运单节点,解析失败.");
}
}else {
log.info("@[四零三]缺少航班信息节点,解析失败");
}
}else {
log.info("@[四零二]缺少回执内容节点,解析失败");
}
}
}else {
log.info("@[四零一]@缺少Manifest或Head节点");
}
}
}
}
}
}catch (Exception e){
log.info("!!!回执解析异常:{}!!!",e.toString());
log.error("!!!处理消息出错:{}!!!",e.toString());
e.printStackTrace();
}
}
/**
* feign从服务直接发送消息
*/
public boolean sendMsgByFeign(MSG msg){
MSGS msgs = new MSGS();
msg.getHEADER().setSNDR("HYYW");
msgs.setMSG(msg);
ResultJson response = kafkaSendApi.send(msgs);
if ("200".equals(response.getCode())){
log.info("………………6-消息发送成功{}………………",response.toString());
return true;
}
log.info("400-消息发送失败->{}",response.toString());
return false;
}
/**
* feign重发消息
*/
public void reTrySend(MSG msg){
log.error("***进入重发***");
for (int i = 0; i < RETRY_TIMES; i++) {
Boolean sendResult = sendMsgByFeign(msg);
if (sendResult){
log.error("***重发成功***");
break;
}
if (i>85){
log.error("***重发{}次未成功,执行重新登录尝试***",i);
login();
break;
}
log.error("***已尝试重发>>>{}<<<次,重发失败***",i);
}
}
/**
* 读取备份消息并消息重发
* @return
*/
public void reSend(MSG msg){
log.error("***进入重发***");
for (int i = 0; i < RETRY_TIMES; i++) {
Boolean sendResult = sendMsg(msg);
if (sendResult){
log.error("***重发成功***");
break;
}
if (i>85){
log.error("***重发{}次未成功,执行重新登录尝试***",i);
login();
break;
}
log.error("***已尝试重发>>>{}<<<次,重发失败***",i);
}
}
}