审查视图

src/main/java/com/tianbo/messagebus/service/MessageBusProcessor.java 16.8 KB
朱兆平 authored
1 2 3 4 5
package com.tianbo.messagebus.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
6 7 8 9 10 11
import com.tianbo.messagebus.controller.response.ResultJson;
import com.tianbo.messagebus.model.HEADER;
import com.tianbo.messagebus.model.MSG;
import com.tianbo.messagebus.model.MSGS;
import com.tianbo.messagebus.myinterface.KafkaReciveApi;
import com.tianbo.messagebus.myinterface.KafkaSendApi;
朱兆平 authored
12
import lombok.extern.slf4j.Slf4j;
13
import org.springframework.beans.factory.annotation.Autowired;
朱兆平 authored
14 15 16 17 18 19 20 21 22 23 24 25 26
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
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;
27
import java.util.List;
朱兆平 authored
28 29

@Service
30
//@EnableAsync
朱兆平 authored
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
@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;
朱兆平 authored
80 81 82
    /**
     * 失败重发请求次数
     */
83
    private static final int RETRY_TIMES= 100;
朱兆平 authored
84 85 86 87 88 89 90

    /**
     * HTTP请求框架
     */
    @Resource
    private RestTemplate restTemplate;
91 92 93 94 95 96
    @Autowired
    KafkaReciveApi kafkaReciveApi;

    @Autowired
    KafkaSendApi kafkaSendApi;
朱兆平 authored
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
    /**
     * 发起登录,存储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();
        }
    }
朱兆平 authored
196 197 198 199 200 201 202 203 204 205 206
    /**
     * 获取返回信息的状态码
     * @param response response对象
     * @return
     */
    private String  getResponseDataCode(ResponseEntity<String> response){
        JSONObject resJson = JSON.parseObject(response.getBody());
        String code = resJson.getString("code");

        return code;
    }
207
//    @Scheduled(fixedDelay = 10000)
朱兆平 authored
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    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);
朱兆平 authored
232
朱兆平 authored
233
            //  输出结果
朱兆平 authored
234 235
            log.info(response.getBody());
朱兆平 authored
236
            if (response.getStatusCode().equals(HttpStatus.OK)) {
朱兆平 authored
237
                log.info("心跳成功,token:[{}]",TOKEN);
朱兆平 authored
238 239 240 241 242 243 244 245 246 247 248 249 250
            } else {
                log.error("心跳失败");
            }
        }
    }

    /**
     * 发送消息
     *
     * @return
     */
    public Boolean sendMsg(MSG msg) {
        if (LOGIN_STATUS) {
朱兆平 authored
251
            try{
252
                log.info("………………开始发送消息:{}………………",msg.toString());
朱兆平 authored
253 254 255 256 257 258
                /*
                 * 发起HTTP 登录请求
                 * 登录接口的请求头为application/json
                 */
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
朱兆平 authored
259
朱兆平 authored
260 261
                MSGS msgs = new MSGS();
                msg.getHEADER().setSNDR("HYYW");
朱兆平 authored
262
朱兆平 authored
263
                msgs.setMSG(msg);
朱兆平 authored
264 265 266 267 268 269 270 271 272 273 274 275 276


            /*
                设置要发送的实体类并将实体转换成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));
朱兆平 authored
277 278 279 280
                /*
                 * 设置获取到的token到头部信息Authorization节点中
                 */
                headers.setBearerAuth(TOKEN);
朱兆平 authored
281
朱兆平 authored
282 283 284
                /*
                 * 发起消息接口访问,发送消息
                 */
朱兆平 authored
285
朱兆平 authored
286 287 288 289 290 291
                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)) {
292
                        log.info("………………消息发送成功………………");
朱兆平 authored
293 294 295 296 297 298 299
                        return true;
                    }
                }
                log.info("消息发送失败->{}",response.getBody());
            }catch (Exception e){
                log.info("消息发送失败->{},失败原因:{}",msg.toString(),e.toString());
                log.error("消息发送失败->{},失败原因:{}",msg.toString(),e.toString());
朱兆平 authored
300 301
                return false;
            }
朱兆平 authored
302 303
        }else {
            log.info("未登陆,消息发送失败");
朱兆平 authored
304 305 306 307 308 309 310 311 312 313
        }
        return false;
    }


    /**
     * 收取消息
     *
     * @return
     */
朱兆平 authored
314
//    @Async
315
//    @Scheduled(fixedRate = 1000)
朱兆平 authored
316 317 318 319 320 321 322 323 324
    public JSONArray getMsg() {
        if(!LOGIN_STATUS){
            login();
            return null;
        }
        /*
         * 发起HTTP 登录请求
         * 登录接口的请求头为application/json
         */
朱兆平 authored
325 326 327 328 329 330 331 332 333 334
        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);
朱兆平 authored
335
朱兆平 authored
336 337 338 339 340
            /*
             * 提交HTTP访问,获取返回信息
             */
            ResponseEntity<String> response = restTemplate.postForEntity(GET_MSG_URL, request, String.class);
            //  输出结果
341
            log.info("接口访问结果:{}",response);
朱兆平 authored
342
朱兆平 authored
343
            if (response.getStatusCode().equals(HttpStatus.OK)) {
朱兆平 authored
344
                /*
朱兆平 authored
345
                 * 从返回信息中确定是否获取到消息
朱兆平 authored
346
                 */
朱兆平 authored
347 348 349 350 351
                JSONObject resJson = JSON.parseObject(response.getBody());
                String code = resJson.getString("code");
                if ("200".equals(code)){
                    JSONArray data = resJson.getJSONArray("data");
                    log.info("消息接收成功,接收消息数量>>>{}<<<",data.size());
朱兆平 authored
352
朱兆平 authored
353 354 355 356 357
                    for (int i = 0; i<data.size() ; i++) {
                /*
                    取得是大数据小组的实体,他们的msg.body的封装是以对象实体object封装的。不是json字符串。
                 */
                        String msg = data.getObject(i,String.class);
358
                        log.info("循环处理消息[{}]---{}---",i,msg);
朱兆平 authored
359 360 361
                        JSONObject rootJson = JSON.parseObject(msg);
                        JSONObject msgJson = rootJson.getJSONObject("MSG");
                        JSONObject body = msgJson.getJSONObject("BODY");
朱兆平 authored
362
朱兆平 authored
363
                        HEADER msgHeader = msgJson.getObject("HEADER",HEADER.class);
朱兆平 authored
364
朱兆平 authored
365 366 367 368
                        MSG transMsg=  new MSG();
                        String transBody = body.toJSONString();
                        transMsg.setHEADER(msgHeader);
                        transMsg.setBODY(transBody);
朱兆平 authored
369 370 371 372

                /*
                    自定义对返回数据的处理
                */
朱兆平 authored
373 374 375 376 377 378 379 380 381 382 383 384
                        log.info("开始转发消息");
                        Boolean sendResult = sendMsg(transMsg);
                        /**
                         * todo:转发消息失败处理
                         */
                        if(!sendResult){
                            log.error("!!!!!!消息--->{}<---转发失败!!!!!!,尝试重发",transMsg.toString());
                            //todo:消息备份或者重发?
                            reSend(transMsg);
                        }
                    }
                    return data;
朱兆平 authored
385
                }
朱兆平 authored
386 387 388
            } else {
                log.error("消息获取失败");
                return new JSONArray();
朱兆平 authored
389
            }
朱兆平 authored
390 391 392
        }catch (Exception httpE){
            log.info("消息获取失败,失败原因:{}",httpE.toString());
            log.error("消息获取失败,失败原因:{}",httpE.toString());
朱兆平 authored
393 394

        }
朱兆平 authored
395
        return new JSONArray();
朱兆平 authored
396 397 398
    }

    /**
399
     * feigin从服务直接获取消息
朱兆平 authored
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
    @Scheduled(fixedRate = 1000)
    public void getDataFromFeigin(){

        log.info("1-开始执行获取任务");
        ResultJson<List<String>> listResultJson = kafkaReciveApi.recive("HYYW");
        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);

                MSG transMsg=  new MSG();
                String transBody = body.toJSONString();
                transMsg.setHEADER(msgHeader);
                transMsg.setBODY(transBody);

                log.info("5-开始转发消息");
                boolean sendResult = sendMsgByFeign(transMsg);
                if(!sendResult){
                    log.error("!!!!!!消息--->{}<---转发失败!!!!!!,尝试重发",transMsg.toString());
                    //todo:消息备份或者重发?
                    reTrySend(transMsg);
                }
朱兆平 authored
431 432
            }
        }
朱兆平 authored
433 434 435 436

    }

    /**
437
     * feign从服务直接发送消息
朱兆平 authored
438
     */
439 440 441
    public boolean sendMsgByFeign(MSG msg){
        MSGS msgs = new MSGS();
        msg.getHEADER().setSNDR("HYYW");
朱兆平 authored
442
443
        msgs.setMSG(msg);
朱兆平 authored
444
445
        ResultJson response = kafkaSendApi.send(msgs);
朱兆平 authored
446
447 448 449 450 451 452
        if ("200".equals(response.getCode())){
            log.info("………………6-消息发送成功{}………………",response.toString());
            return true;
        }
        log.info("400-消息发送失败->{}",response.toString());
        return  false;
朱兆平 authored
453
    }
朱兆平 authored
454 455

    /**
456
     * feign重发消息
朱兆平 authored
457
     */
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
    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);
        }
    }
朱兆平 authored
474
    /**
475 476
     * 读取备份消息并消息重发
     * @return
朱兆平 authored
477
     */
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
    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);
        }
朱兆平 authored
493 494 495 496 497

    }


498
}
朱兆平 authored
499 500 501 502 503 504 505 506