소스 검색

算法调用代码优化

linfutong 2 년 전
부모
커밋
81a0e9b8be

+ 40 - 4
zd-modules/zd-algorithm/src/main/java/com/zd/alg/forward/controller/SignInCheckController.java

@@ -12,6 +12,8 @@ import com.zd.common.core.exception.ServiceException;
 import com.zd.common.core.redis.RedisService;
 import com.zd.common.core.utils.Assert;
 import com.zd.common.swagger.config.Knife4jConfiguration;
+import com.zd.model.constant.BaseConstants;
+import com.zd.model.constant.HttpStatus;
 import com.zd.model.domain.R;
 import com.zd.model.entity.Algorithm;
 import io.swagger.annotations.Api;
@@ -67,6 +69,11 @@ public class SignInCheckController {
     @ApiOperation(value = "进入项验证")
     @PostMapping("/{code}/{id}")
     public R checkIn(@ApiParam("进出记录ID") @PathVariable("id") Long id, @ApiParam("验证类型编码") @PathVariable("code") String code, @RequestParam("file") MultipartFile file) {
+        //检查签到
+        R result = checkSignInOrOut(id);
+        if (result.getCode() != HttpStatus.SUCCESS) {
+            return result;
+        }
         return checkService.checkAndCommit(code, file, id);
     }
 
@@ -81,6 +88,11 @@ public class SignInCheckController {
     public R checkInAll(@ApiParam("进出记录ID") @RequestParam("id") Long id,
                         @ApiParam("图片文件") @RequestParam("file") MultipartFile file,
                         @ApiParam("实验室ID") @RequestParam("subId") Long subId) {
+        //检查签到
+        R result = checkSignInOrOut(id);
+        if (result.getCode() != HttpStatus.SUCCESS) {
+            return result;
+        }
         return checkService.checkAndCommit(id, file, subId);
     }
 
@@ -94,6 +106,11 @@ public class SignInCheckController {
     @ApiOperation(value = "进入项验证:mock方法")
     @PostMapping("/mock/{code}/{id}")
     public R checkInMock(@ApiParam("进出记录ID") @PathVariable("id") Long id, @ApiParam("验证类型编码") @PathVariable("code") String code, @RequestParam("file") MultipartFile file) {
+        //检查签到
+        R result = checkSignInOrOut(id);
+        if (result.getCode() != HttpStatus.SUCCESS) {
+            return result;
+        }
         return checkService.mockTest(code, file, id);
     }
 
@@ -127,11 +144,11 @@ public class SignInCheckController {
     @PostMapping("/alarmCallBack")
     public R fireCallBack(@RequestBody VideoRequestData videoRequestData) {
         Integer aid = videoRequestData.getAid();
-        if (aid!=null){
-            if (aid.equals(9610)){
-                logger.info("=====================>测试回调了。。。{}",videoRequestData.getAlgo_name());
+        if (aid != null) {
+            if (aid.equals(9610)) {
+                //logger.info("=====================>测试回调了。。。{}",videoRequestData.getAlgo_name());
                 checkService.sendAlarm(videoRequestData);
-            }else if (aid.equals(9690)){
+            } else if (aid.equals(9690)) {
                 checkService.playMp3();
             }
         }
@@ -163,4 +180,23 @@ public class SignInCheckController {
     public R checkFire(@ApiParam("图片文件") @RequestParam("file") MultipartFile file) {
         return R.ok(fireImageService.catchImage(file));
     }
+
+    /**
+     * 检查签到/签退
+     * @param id
+     * @return
+     */
+    private R checkSignInOrOut(Long id) {
+        //检查签到
+        Long value = redisService.getCacheObject(BaseConstants.SINGIN_id_KEY + id);
+        if (value != null) {
+            //刷新key
+            boolean expire = redisService.expire(BaseConstants.SINGIN_id_KEY + id, BaseConstants.SINGIN_OUT_TIME);
+            if (!expire) {
+                return R.fail(600, "签到&签出已超时,请刷卡重试!");
+            }
+            return R.ok();
+        }
+        return R.fail(600, "签到&签出已超时,请刷卡重试!");
+    }
 }

+ 23 - 142
zd-modules/zd-algorithm/src/main/java/com/zd/alg/forward/serivce/CheckService.java

@@ -23,6 +23,7 @@ import com.zd.common.core.utils.ServletUtils;
 import com.zd.common.core.utils.StringUtils;
 import com.zd.laboratory.api.feign.RemoteLaboratoryService;
 import com.zd.model.constant.BaseConstants;
+import com.zd.model.constant.HttpStatus;
 import com.zd.model.constant.SecurityConstants;
 import com.zd.model.domain.R;
 import com.zd.model.entity.Algorithm;
@@ -95,15 +96,9 @@ public class CheckService {
     public R checkAndCommit(Long id, MultipartFile file, Long subId) {
         try {
             int alarmNum = 0;
-            //========= 请求超时验证部分开始 ===========
-            //600 则代表退出验证流程 需要重新刷卡
-            R<Long> fail = getObjectR(id);
-            if (fail.getCode() != 200) {
-                return fail;
-            }
             //根据实验室id查询检查项
             R<Map<Object, Object>> subject = laboratoryService.getCheckInfo(subId);
-            if (subject.getCode() != 200) {
+            if (subject.getCode() != HttpStatus.SUCCESS) {
                 return subject;
             }
             Map<Object, Object> map = subject.getData();
@@ -114,8 +109,7 @@ public class CheckService {
             //上传原始图片
             String orgImgUrl = "";
             R<SysFile> r = remoteFileService.upload(file);
-            //logger.info("【调用算法服务】 原文件上传结果:"+JSONObject.toJSONString(r));
-            if (r.getCode() == 200) {
+            if (r.getCode() == HttpStatus.SUCCESS) {
                 orgImgUrl = r.getData().getUrl();
             }
             String labSkipped = "0";
@@ -142,12 +136,8 @@ public class CheckService {
                 ImgPostResponse<AnalysisReturnData> send = HttpUtils.sendV5(restTemplateLocal, files, algorithmYml);
                 //算法记录更新
                 if (alg.getCode() == 200) {
-                    try {
-                        updateRequestRecordLog(alg.getData() != null?Long.valueOf(alg.getData()+""):null, send);
-                        logger.info("【调用算法服务】 更新算法调用日志");
-                    } catch (Exception e) {
-                        logger.error("【调用算法服务】 更新日志异常,异常信息",e);
-                    }
+                    updateRequestRecordLog(alg.getData() != null?Long.valueOf(alg.getData()+""):null, send);
+                    logger.info("【调用算法服务】 更新算法调用日志记录");
                 }
                 //判断算法
                 if (send == null || send.getStatus_code() != 1000) {
@@ -187,7 +177,7 @@ public class CheckService {
                 return R.ok();
             }
         } catch (Exception e) {
-            logger.error("【算法服务异常】异常信息",e);
+            logger.error("【调用算法服务】 算法服务调用发生异常", e);
         }
         return R.fail();
     }
@@ -245,16 +235,23 @@ public class CheckService {
             algorithm.setStatus(0);
         }
         //存原始数据
-        AnalysisReturnData respData = send != null?send.getData():null;
-        if (respData != null) {
-            respData.setRet_image("Removed to save respBody");
-            respData.setSrc_image("Removed to save respBody");
-            ImgPostResponse<AnalysisReturnData> response = new ImgPostResponse<>();
-            response.setData(respData);
-            response.setStatus_code(send.getStatus_code());
-            response.setMessage(send.getMessage());
-            algorithm.setRespData(JSONObject.toJSONString(response));
+        if (send != null) {
+            if (send.getData() != null) {
+                AnalysisReturnData respData = send.getData();
+                respData.setRet_image("");
+                respData.setSrc_image("");
+                ImgPostResponse<AnalysisReturnData> response = new ImgPostResponse<>();
+                response.setData(respData);
+                response.setStatus_code(send.getStatus_code());
+                response.setMessage(send.getMessage());
+                algorithm.setRespData(JSONObject.toJSONString(response));
+            } else {
+                algorithm.setRespData(JSONObject.toJSONString(send));
+            }
             algorithm.setRespCode(send.getStatus_code());
+        } else {
+            algorithm.setRespCode(0L);
+            algorithm.setRespData("算法服务未响应");
         }
         algorithm.setUpdateTime(new Date());
         //logger.info("【算法服务】 更新日志实体信息:"+JSONObject.toJSONString(algorithm));
@@ -265,13 +262,7 @@ public class CheckService {
      * @param id 进出记录ID
      */
     public R checkAndCommit(String code, MultipartFile file, Long id) {
-        //========= 请求超时验证部分开始 ===========
-        //600 则代表退出验证流程 需要重新刷卡
-        R<Long> fail = getObjectR(id);
-        if (fail.getCode() != 200) {
-            return fail;
-        }
-        //========= 请求超时验证部分结束 ===========
+
         //========= 获取算法INFO ===========
         AlgorithmYml.CheckValid checkValid = algorithmYml.getCheckValid(Integer.valueOf(code));
         //=========发送验证信息到算法服务开始
@@ -363,22 +354,6 @@ public class CheckService {
         return algorithm;
     }
 
-    public Algorithm CovertV5(Map<String, Object> data) {
-        Algorithm algorithm = new Algorithm();
-        algorithm.setId(Long.valueOf(data.get("id").toString()));
-        algorithm.setAlgorithmType(data.get("type").toString());
-        algorithm.setAlgorithmResult(data.get("src_img").toString());
-        algorithm.setSubId(Long.valueOf(data.get("aid").toString()));
-        algorithm.setSignId(Long.valueOf(data.get("cid").toString()));
-        algorithm.setAlgorithmName(data.get("algorithmName").toString());
-        algorithm.setIsAlarm(Integer.parseInt(data.get("isAlarm").toString()));
-        algorithm.setOriginalImg(data.get("originalImg").toString());
-        algorithm.setRespData(data.get("requestData").toString());
-        algorithm.setUpdateTime(new Date());
-        algorithm.setStatus(0);
-        return algorithm;
-    }
-
     /**
      * @param algorithmResult
      * @param type
@@ -453,25 +428,8 @@ public class CheckService {
     }
 
 
-    private R<Long> getObjectR(Long id) {
-        Long subId = redisService.getCacheObject(BaseConstants.SINGIN_id_KEY + id);
-        if (subId == null) {
-            return R.fail(600, "签到&签出已超时,请重新刷卡重试!");
-        }
-        //刷新key
-        boolean expire = redisService.expire(BaseConstants.SINGIN_id_KEY + id, 120);
-        if (!expire) {
-            return R.fail(600, "签到&签出已超时,请重新刷卡重试!");
-        }
-        return R.ok(subId);
-    }
-
     //给黎晨用的模拟方法 他让给他mock个方法测试
     public R mockTest(String code, MultipartFile file, Long id) {
-        R<Long> objectR = getObjectR(id);
-        if (objectR.getCode() != 200) {
-            return objectR;
-        }
         //随机成功或失败
         Boolean f = RandomUtil.randomInt(0, 2) == 0;
         //无论成功失败,插入记录数据,异步请求远程接口
@@ -493,7 +451,6 @@ public class CheckService {
 
     }
 
-
     public void send(String code, Long id, Boolean f, String msg) {
         String token = Objects.requireNonNull(ServletUtils.getRequest()).getHeader(SecurityConstants.TOKEN_AUTHENTICATION);
         if (CharSequenceUtil.isBlank(token)) {
@@ -591,80 +548,4 @@ public class CheckService {
             return null;
         }
     }
-
-    /**
-     * 存储数据
-     *
-     * @param send
-     * @param checkValid
-     */
-    private R saveAlgorithm(ImgPostResponse<DataPostAnalysisRespDto> send, AlgorithmYml.CheckValid checkValid) {
-        DataPostAnalysisRespDto analysisRespDto = send.getData();
-        List<AnalysisData> analysisDatas = analysisRespDto.getAnalysisDatas();
-        if (!analysisDatas.isEmpty()) {
-            for (AnalysisData data : analysisDatas) {
-                String picture = data.getRet_image();
-                String header = "data:image/jpeg;base64," + picture;
-                MultipartFile multipartFile = Base64DecodedMultipartFile.base64ToMultipart(header);
-                R<SysFile> sysFileR = remoteFileService.upload(multipartFile);
-                String imageUrl = sysFileR.getData().getUrl();
-                Map<String, Object> result = (Map<String, Object>) data.getResult();
-                Map<String, Object> map = new HashMap<>();
-                Map<String, Object> algorithmData = (Map<String, Object>) result.get("algorithm_data");
-                Map<String, Object> modelResult = (Map<String, Object>) result.get("model_data");
-                List<Map<String, Object>> objects = (List<Map<String, Object>>) modelResult.get("objects");
-                if (algorithmData.getOrDefault("is_alert", "").toString().equals("false") && objects.size() > 0) {
-                    map.put("isAlarm", 0);
-                } else {
-                    map.put("isAlarm", 1);
-                }
-                map.put("did", checkValid.getDid());
-                map.put("aid", checkValid.getAlgoId());
-                map.put("src_img", imageUrl);
-                map.put("type", "image");
-                map.put("algorithmName", checkValid.getAlgorithmName());
-                return laboratoryService.saveData(Covert(map));
-            }
-        }
-        logger.error("接口数据返回异常");
-        throw new ServiceException("接口数据返回异常");
-    }
-
-
-    /**
-     * 存储数据
-     * @param send
-     * @param checkValid
-     */
-    private R saveAlgorithmV5(Long id,MultipartFile file,ImgPostResponse<AnalysisReturnData> send,AlgorithmYml.CheckValid checkValid){
-        String picture = send.getData().getRet_image();
-        String header = "data:image/jpeg;base64,"+picture;
-        MultipartFile multipartFile = Base64DecodedMultipartFile.base64ToMultipart(header);
-        R<SysFile> sysFileR = remoteFileService.upload(multipartFile);
-        String imageUrl = sysFileR.getData().getUrl();
-        logger.info("==================================imageUrl:"+imageUrl);
-        AnalysisReturnData data =  send.getData();
-        Map<String, Object> map =new HashMap<>();
-        Map<String, Object> result =(Map<String, Object>)data.getResult();
-        Map<String, Object> algorithmData = (Map<String, Object>) result.get("algorithm_data");
-        Map<String, Object> modelResult = (Map<String, Object>) result.get("model_data");
-        List<Map<String, Object>> objects = (List<Map<String, Object>>) modelResult.get("objects");
-        if(algorithmData.getOrDefault("is_alert", "").toString().equals("false") && objects.size()>0){
-            map.put("isAlarm", 0);
-        }else{
-            map.put("isAlarm", 1);
-        }
-        map.put("isAlarm", 1);
-        map.put("aid", data.getAid());
-        map.put("cid", data.getCid());
-        map.put("src_img", imageUrl);
-        //map.put("originalImg", originalUrl);
-        map.put("type", "image");
-        map.put("algorithmName", checkValid.getAlgorithmName());
-        map.put("id",id);
-        map.put("requestData", JSONObject.toJSONString(send));
-        logger.info("=======================map.tostring()"+map.toString());
-        return laboratoryService.saveAlgorithmData(CovertV5(map));
-       // return laboratoryService.update(CovertV5(map));
-    }
 }

+ 7 - 6
zd-modules/zd-algorithm/src/main/java/com/zd/alg/forward/utils/HttpUtils.java

@@ -129,16 +129,17 @@ public class HttpUtils {
         return null;
     }
 
+    /**
+     * 调用算法服务
+     * @param restTemplate
+     * @param files
+     * @param algorithmYml
+     * @return
+     */
     public static ImgPostResponse<AnalysisReturnData> sendV5(RestTemplate restTemplate, HttpEntity<MultiValueMap<String, Object>> files, AlgorithmYml algorithmYml) {
         ParameterizedTypeReference<ImgPostResponse<AnalysisReturnData>> reference = new ParameterizedTypeReference<ImgPostResponse<AnalysisReturnData>>() {
         };
         ResponseEntity<ImgPostResponse<AnalysisReturnData>> response = restTemplate.exchange(algorithmYml.getImgPostUrl(), HttpMethod.POST, files, reference);
-        if (response.getStatusCode() != HttpStatus.OK) {
-            log.error("算法服务请求异常,请查看算服务器");
-        }
-        if (response.getBody() == null) {
-            log.error("算法服务接口返回异常");
-        }
         return response.getBody();
     }
 }