hecheng пре 3 година
родитељ
комит
056817e107

+ 10 - 1
zd-common/zd-common-core/src/main/java/com/zd/common/core/constant/Constants.java

@@ -115,7 +115,7 @@ public class Constants {
     /**
      * 令牌有效期(分钟)
      */
-    public final static long TOKEN_EXPIRE = 720;
+    public static final long TOKEN_EXPIRE = 720;
 
     /**
      * 参数管理 cache key
@@ -142,10 +142,19 @@ public class Constants {
      * 删除状态标记
      */
     public static final String DEL = "2";
+
+    /**
+     * baskPackage
+     */
+    public static final String BASE_PACKAGE = "com.zd";
     /**
      * 正常状态标记
      */
     public static final String NORMAL = "0";
+    /**
+     * MAP集合的初始化大小
+     */
+    public static final Integer MAP_INIT_SIZE = 16;
 
 
 

+ 13 - 7
zd-modules/zd-forward/src/main/java/com/zd/forward/ForwardApp.java

@@ -1,5 +1,7 @@
 package com.zd.forward;
 
+import com.zd.common.core.constant.Constants;
+import com.zd.common.core.properties.SnowflakeProperties;
 import com.zd.common.security.annotation.EnableCustomConfig;
 import com.zd.common.security.annotation.EnableRyFeignClients;
 import com.zd.forward.properties.FireProperties;
@@ -12,18 +14,22 @@ import org.springframework.context.ConfigurableApplicationContext;
 import springfox.documentation.oas.annotations.EnableOpenApi;
 import zd.common.mqtt.config.MqttProperties;
 
+/**
+ * @author Administrator
+ */
 @EnableCustomConfig
 @EnableRyFeignClients
-@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
-@EnableConfigurationProperties({MqttProperties.class, FireProperties.class})
+@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class},scanBasePackages = {Constants.BASE_PACKAGE})
+@EnableConfigurationProperties({MqttProperties.class, FireProperties.class, SnowflakeProperties.class})
 @EnableOpenApi
 public class ForwardApp {
 
     public static void main(String[] args) {
-        ConfigurableApplicationContext run = SpringApplication.run(ForwardApp.class, args);
-        //获取token
-        LoginService bean = run.getBeanFactory().getBean(LoginService.class);
-        bean.loginLab();
-        System.out.println("(♥◠‿◠)ノ゙ 转发服务启动! ლ(´ڡ`ლ)゙");
+        try (ConfigurableApplicationContext run = SpringApplication.run(ForwardApp.class, args)){
+            //获取token
+            LoginService bean = run.getBeanFactory().getBean(LoginService.class);
+            bean.loginLab();
+            System.out.println("(♥◠‿◠)ノ゙ 转发服务启动! ლ(´ڡ`ლ)゙");
+        }
     }
 }

+ 15 - 12
zd-modules/zd-forward/src/main/java/com/zd/forward/listener/StartListener.java

@@ -2,11 +2,13 @@ package com.zd.forward.listener;
 
 import com.zd.forward.serivce.FireImageService;
 import lombok.extern.slf4j.Slf4j;
-import org.springframework.boot.ApplicationArguments;
-import org.springframework.boot.ApplicationRunner;
+import org.apache.commons.lang3.concurrent.BasicThreadFactory;
+import org.springframework.boot.CommandLineRunner;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.Resource;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
 
 /**
  * 监听Spring容器启动完成,完成后启动Netty服务器
@@ -15,20 +17,21 @@ import javax.annotation.Resource;
  **/
 @Component
 @Slf4j
-public class StartListener implements ApplicationRunner {
+public class StartListener implements CommandLineRunner {
     @Resource
     private FireImageService fireImageService;
 
     @Override
-    public void run(ApplicationArguments args) {
+    public void run(String... args) {
         //未验证部分,待验证后启用
-//        new Thread(new Runnable() {
-//            @Override
-//            public void run() {
-//                synchronized (this){
-//                    fireImageService.catchImage();
-//                }
-//            }
-//        }).start();
+        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("fire-pool-%d").daemon(true).build());
+        executorService.execute(new Runnable() {
+            @Override
+            public void run() {
+                synchronized (this){
+                    fireImageService.catchImage();
+                }
+            }
+        });
     }
 }

+ 8 - 3
zd-modules/zd-forward/src/main/java/com/zd/forward/properties/FireProperties.java

@@ -7,6 +7,9 @@ import org.springframework.validation.annotation.Validated;
 
 import javax.validation.constraints.NotNull;
 
+/**
+ * @author Administrator
+ */
 @ConfigurationProperties("fire")
 @RefreshScope
 @Validated
@@ -15,8 +18,10 @@ public class FireProperties {
 
     @NotNull(message = "算法ID不能为空")
     private Integer algoId;
-    //cid
-    @NotNull (message = "=数据ID不能为空")
+    /**
+     * did 数据ID
+     */
+    @NotNull (message = "数据ID不能为空")
     private String did;
 
     /**
@@ -36,7 +41,7 @@ public class FireProperties {
     /**
      * 视频流地址
      */
-    private String streamURL;
+    private String streamUrl;
 
     /**
      * 间隔时间

+ 23 - 25
zd-modules/zd-forward/src/main/java/com/zd/forward/serivce/FireImageService.java

@@ -31,6 +31,7 @@ import static com.zd.forward.util.HttpUtils.getHttpEntityMap;
 
 /**
  * 火焰图片抓拍处理
+ * @author Administrator
  */
 @Service
 @Slf4j
@@ -46,21 +47,22 @@ public class FireImageService {
     @Resource
     private SendSginAccessLogService sendSginAccessLogService;
 
+    private static final Integer SUCCESS_CODE=1000;
+
     /**
      * 上传文件存储在本地的根路径
      */
     @Value("${file.path:/home/AIPIC}")
     private String imagePath;
 
-    public void catchImage(){
+    public void catchImage() {
 
-        String streamURL = fireProperties.getStreamURL();
-        if (streamURL==null){
+        String streamUrl = fireProperties.getStreamUrl();
+        if (streamUrl == null) {
             throw new ServiceException("未配置流媒体地址");
         }
 
-        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(streamURL);
-        try {
+        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(streamUrl)) {
             grabber.start();
             //获取第一帧
             Frame frame = grabber.grabFrame();
@@ -71,9 +73,9 @@ public class FireImageService {
                     frame = grabber.grabImage();
                     long uuid = IdGen.snowflakeId();
                     //文件储存对象
-                    String fileName = imagePath+File.pathSeparator + uuid + "_" + flag;
+                    String fileName = imagePath + File.separator + uuid + "_" + flag;
                     File tempFile = File.createTempFile(fileName, ".jpg");
-                    ImageIO.write(FrameToBufferedImage(frame), "jpg", tempFile);
+                    ImageIO.write(frameToBufferedImage(frame), "jpg", tempFile);
                     send(tempFile);
                 }
                 //停止
@@ -81,33 +83,28 @@ public class FireImageService {
             }
         } catch (IOException e) {
             e.printStackTrace();
-        } finally {
-            try {
-                grabber.stop();
-            } catch (FrameGrabber.Exception e) {
-                e.printStackTrace();
-            }
+            throw new ServiceException(e.getMessage());
         }
     }
 
-    private void send(File file){
-        if (fireProperties.getAlgoId()==null){
+    private void send(File file) {
+        if (fireProperties.getAlgoId() == null) {
             throw new ServiceException("未配置火焰算法ID");
         }
         MultiValueMap<String, Object> params = HttpUtils.getMultiValueMap(fireProperties, null);
-        HttpEntity<MultiValueMap<String, Object>> files=getHttpEntityMap(file,params);
-        ImgPostResponse<DataPostAnalysisRespDto> send = HttpUtils.send(restTemplateLocal,files,algorithmYml);
-        if (send == null || send.getStatus_code() != 1000) {
+        HttpEntity<MultiValueMap<String, Object>> files = getHttpEntityMap(file, params);
+        ImgPostResponse<DataPostAnalysisRespDto> send = HttpUtils.send(restTemplateLocal, files, algorithmYml);
+        if (send == null || send.getStatus_code() != SUCCESS_CODE) {
             assert send != null;
             log.error(send.getMessage());
             throw new ServiceException(send.getMessage());
         }
         DataPostAnalysisRespDto data = send.getData();
 
-        Map<String,Object> result = (Map<String, Object>) Optional.ofNullable(data.getAnalysisDatas().get(0).getResult()).orElse(Collections.emptyMap());
-        Map<String,Object> algorithmData = (Map<String, Object>)  Optional.ofNullable(result.get("algorithm_data")).orElse(Collections.emptyMap());
-        boolean alert = algorithmData.getOrDefault("is_alert", "").toString().equals("false");
-        if (!alert){
+        Map<String, Object> result = (Map<String, Object>) Optional.ofNullable(data.getAnalysisDatas().get(0).getResult()).orElse(Collections.emptyMap());
+        Map<String, Object> algorithmData = (Map<String, Object>) Optional.ofNullable(result.get("algorithm_data")).orElse(Collections.emptyMap());
+        boolean alert = "false".equals(algorithmData.getOrDefault("is_alert", "").toString());
+        if (!alert) {
             sendSginAccessLogService.saveAlarm(fireProperties);
         }
     }
@@ -115,9 +112,10 @@ public class FireImageService {
     /**
      * frame 转图片流
      */
-    public static BufferedImage FrameToBufferedImage(Frame frame) {
+    public static BufferedImage frameToBufferedImage(Frame frame) {
         //创建BufferedImage对象
-        Java2DFrameConverter converter = new Java2DFrameConverter();
-        return converter.getBufferedImage(frame);
+        try (Java2DFrameConverter converter = new Java2DFrameConverter()){
+            return converter.getBufferedImage(frame);
+        }
     }
 }

+ 20 - 20
zd-modules/zd-forward/src/main/java/com/zd/forward/serivce/SendSginAccessLogService.java

@@ -30,6 +30,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
 
+import static com.zd.common.core.constant.Constants.MAP_INIT_SIZE;
+
 @Service
 public class SendSginAccessLogService {
 
@@ -123,7 +125,7 @@ public class SendSginAccessLogService {
         String loudspeakerIp1 = algorithmYml.getLoudspeakerIp1();
         String loudspeakerIp2 = algorithmYml.getLoudspeakerIp2();
         R deviceList = remoteSpeakService.getDeviceList(1, 10, 5L);
-        if (deviceList.getCode() == 200) {
+        if (deviceList.getCode() == HttpStatus.SUCCESS) {
             List<Map<String, Object>> mapList = (List<Map<String, Object>>) deviceList.getData();
             for (Map<String, Object> map : mapList) {
                 if (StringUtils.isNotNull(map.get("deviceSn")) && StringUtils.isNotNull(map.get("port"))) {
@@ -152,22 +154,16 @@ public class SendSginAccessLogService {
      * 发送火焰警报
      */
     public R<Object> sendAlarm(VideoRequestData videoRequestData) {
-        Map<String, Object> requestMap = new HashMap<>();
+        Map<String, Object> requestMap = new HashMap<>(MAP_INIT_SIZE);
         List<Map<String, Object>> maps = new ArrayList<>();
         Integer aid = videoRequestData.getAid();
         Map<Integer, AlgorithmYml.AlarmConfig> alarmConfigMap = algorithmYml.getAlarmConfigMap();
         if (alarmConfigMap.containsKey(aid)) {
             AlgorithmYml.AlarmConfig alarmConfig = alarmConfigMap.get(aid);
-            Map<String, Object> params = new HashMap<>();
+            Map<String, Object> params = new HashMap<>(MAP_INIT_SIZE);
             params.put("hardwareNum", videoRequestData.getCid());
             params.put("val", videoRequestData.getStatus());
-            params.put("funNum", alarmConfig.getFunNum());
-            params.put("describe", alarmConfig.getDescribe());
-            maps.add(params);
-            requestMap.put("functionStatuses", maps);
-            ParameterizedTypeReference<R<Object>> reference = new ParameterizedTypeReference<R<Object>>() {
-            };
-            return send(requestMap, algorithmYml.getTargetUrl() + "laboratory/plan/triggerRiskPlan", HttpMethod.POST, reference);
+            return getParams(requestMap, maps, alarmConfig, params);
         }
         return R.fail("未找到算法");
     }
@@ -176,32 +172,36 @@ public class SendSginAccessLogService {
      * 发送火焰警报
      */
     public R<Object> send(FireProperties properties) {
-        Map<String, Object> requestMap = new HashMap<>();
+        Map<String, Object> requestMap = new HashMap<>(MAP_INIT_SIZE);
         List<Map<String, Object>> maps = new ArrayList<>();
         Integer aid = properties.getAlgoId();
         Map<Integer, AlgorithmYml.AlarmConfig> alarmConfigMap = algorithmYml.getAlarmConfigMap();
         if (alarmConfigMap.containsKey(aid)) {
             AlgorithmYml.AlarmConfig alarmConfig = alarmConfigMap.get(aid);
-            Map<String, Object> params = new HashMap<>();
+            Map<String, Object> params = new HashMap<>(MAP_INIT_SIZE);
             params.put("hardwareNum", properties.getHardwareNum());
             params.put("subId", properties.getLabId());
             params.put("val", 1);
-            params.put("funNum", alarmConfig.getFunNum());
-            params.put("describe", alarmConfig.getDescribe());
-            maps.add(params);
-            requestMap.put("functionStatuses", maps);
-            ParameterizedTypeReference<R<Object>> reference = new ParameterizedTypeReference<R<Object>>() {
-            };
-            return send(requestMap, algorithmYml.getTargetUrl() + "laboratory/plan/triggerRiskPlan", HttpMethod.POST, reference);
+            return getParams(requestMap, maps, alarmConfig, params);
         }
         return R.fail("未找到算法");
     }
 
+    private R<Object> getParams(Map<String, Object> requestMap, List<Map<String, Object>> maps, AlgorithmYml.AlarmConfig alarmConfig, Map<String, Object> params) {
+        params.put("funNum", alarmConfig.getFunNum());
+        params.put("describe", alarmConfig.getDescribe());
+        maps.add(params);
+        requestMap.put("functionStatuses", maps);
+        ParameterizedTypeReference<R<Object>> reference = new ParameterizedTypeReference<R<Object>>() {
+        };
+        return send(requestMap, algorithmYml.getTargetUrl() + "laboratory/plan/triggerRiskPlan", HttpMethod.POST, reference);
+    }
+
     private <T> R<T> send(Map<String, Object> params, String url, HttpMethod method, ParameterizedTypeReference<R<T>> reference) {
         HttpEntity<Map<String, Object>> requestEntity = getMapHttpEntity(params);
         ResponseEntity<R<T>> exchange = restTemplateLocal.exchange(url, method, requestEntity, reference);
         R<T> body = exchange.getBody();
-        if (body != null && body.getCode() == 401) {
+        if (body != null && body.getCode() == HttpStatus.UNAUTHORIZED) {
             requestEntity = getMapHttpEntityLogin(params);
             exchange = restTemplateLocal.exchange(url, method, requestEntity, reference);