Ver código fonte

异常处理 以及测试代码

wanggaokun 1 ano atrás
pai
commit
b9467b5dd3

+ 17 - 21
PHM-admin/phm-netty/src/main/java/com/phm/netty/client/NettyUdpClient.java

@@ -4,6 +4,7 @@ import java.net.InetSocketAddress;
 
 import org.springframework.stereotype.Component;
 
+import com.phm.common.exception.GlobalException;
 import com.phm.netty.client.handler.NettyUdpClientHandler;
 
 import io.netty.bootstrap.Bootstrap;
@@ -31,39 +32,34 @@ public class NettyUdpClient {
         EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
         try {
             Bootstrap clientBootstrap = new Bootstrap();
-            clientBootstrap = clientBootstrap.group(eventLoopGroup);
-            clientBootstrap = clientBootstrap.channel(NioDatagramChannel.class);
-            clientBootstrap = clientBootstrap.option(ChannelOption.SO_BROADCAST, true);
-            // clientBootstrap = clientBootstrap.handler(new NettyUdpClientInitialize(customValue));
-            clientBootstrap = clientBootstrap.handler(new ChannelInitializer<NioDatagramChannel>() {
-                @Override
-                protected void initChannel(NioDatagramChannel ch) {
-                    // 使用 AttributeKey 定义一个键
-                    final AttributeKey<String> key = AttributeKey.valueOf("customKey");
+            clientBootstrap = clientBootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
+                .option(ChannelOption.SO_BROADCAST, true).handler(new ChannelInitializer<NioDatagramChannel>() {
+                    @Override
+                    protected void initChannel(NioDatagramChannel ch) {
+                        // 使用 AttributeKey 定义一个键
+                        final AttributeKey<String> key = AttributeKey.valueOf("customKey");
 
-                    // 获取 Channel 的 Attribute
-                    Attribute<String> attr = ch.attr(key);
+                        // 获取 Channel 的 Attribute
+                        Attribute<String> attr = ch.attr(key);
 
-                    // 设置自定义值
-                    attr.set(customValue);
+                        // 设置自定义值
+                        attr.set(customValue);
 
-                    // 在这里添加你的处理器
-                    ch.pipeline().addLast(new NettyUdpClientHandler());
-                }
-            });
+                        // 在这里添加你的处理器
+                        ch.pipeline().addLast(new NettyUdpClientHandler());
+                    }
+                });
             Channel channel = clientBootstrap.bind(8989).sync().channel();
             // 给服务端发送请求信息
             channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(data), new InetSocketAddress(address, port)))
                 .sync();
-            log.info("channel_id = {} ", channel.id().toString());
-
             // 方式一:查询等待超时 单位s, 超时自动关闭
-            channel.closeFuture().await(10000);
-
+            // channel.closeFuture().await(10000);
             // 方式er:原地等候返回消息,再关闭连接
             channel.closeFuture().sync();
         } catch (Exception e) {
             log.error(e.getMessage());
+            throw new GlobalException("在线下载数据异常,请重新下载");
         } finally {
             log.info("netty client udp close!");
             eventLoopGroup.shutdownGracefully();

+ 9 - 0
PHM-admin/phm-netty/src/main/java/com/phm/netty/client/handler/NettyUdpClientHandler.java

@@ -7,6 +7,7 @@ import javax.annotation.PostConstruct;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
+import com.phm.common.exception.GlobalException;
 import com.phm.netty.domain.Message;
 import com.phm.netty.service.IProcessService;
 
@@ -40,12 +41,19 @@ public class NettyUdpClientHandler extends SimpleChannelInboundHandler<DatagramP
 
     @Override
     protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
+        // String data =
+        // FileUtil.readString("D:\\phm\\dataPath\\csv" + "\\parameterData\\参数数据.json", CharsetUtil.CHARSET_UTF_8);
+        // // TODO 这里测试数据
+        // Message message = new Message();
+        // message.setType(OrderEnum.ORDER_CONFIG.getType()).setTarget("GPHM").setSource("SPHM")
+        // .setData("{\"cmdId\": \"getConfig\", \"params\":" + data + "}");
         // 获取自定义值
         String sortieNo = ctx.channel().attr(AttributeKey.valueOf("customKey")).get().toString();
         final ByteBuf buf = packet.content();
         try {
             log.info("channelId---:{}", ctx.channel().id().toString());
             byte[] bytes = ByteBufUtil.getBytes(buf);
+            // Message msg = Message.getMessage(Message.msgToBytes(message));
             Message msg = Message.getMessage(bytes);
             if (msg == null) {
                 log.info("无数据传输");
@@ -56,6 +64,7 @@ public class NettyUdpClientHandler extends SimpleChannelInboundHandler<DatagramP
             ctx.close();
         } catch (Exception e) {
             log.error("channelRead=={}", e.getMessage());
+            throw new GlobalException("在线下载数据异常,请重新下载");
         }
     }
 

+ 3 - 3
PHM-admin/phm-netty/src/main/java/com/phm/netty/controller/NettyUdpClientController.java

@@ -50,10 +50,10 @@ public class NettyUdpClientController extends BaseController {
     public CommonResult<String> getAirborneInfo(@PathVariable("id") Long id) {
         // TODO 这里入参需要确定
         Message message = new Message();
-        message.setType(OrderEnum.ORDER_CONFIG.getType()).setTarget("GPHM").setSource("SPHM")
-            .setData("{\"cmdId\": \"getConfig\", \"params\": [{\"参数一\":0.1079,\"参数三\":0.6007,\"参数二\":0.0116,\"参数五\":0.0689,\"参数四\":1.1915,\"时间\":\"2022/6/3013:08\"},{\"参数一\":0.8088,\"参数三\":2.9169,\"参数二\":0.6541,\"参数五\":0.6229,\"参数四\":5.5326,\"时间\":\"2022/6/3013:09\"},\t{\"参数一\":0.9088,\"参数三\":2.7169,\"参数二\":0.0541,\"参数五\":0.4229,\"参数四\":3.5326,\"时间\":\"2022/6/3013:10\"}]}");
+        message.setType(OrderEnum.ORDER_CONFIG.getType()).setTarget("GPHM").setSource("SPHM").setData(
+            "{\"cmdId\": \"getConfig\", \"params\": [{\"参数一\":0.1079,\"参数三\":0.6007,\"参数二\":0.0116,\"参数五\":0.0689,\"参数四\":1.1915,\"时间\":\"2022/6/3013:08\"},{\"参数一\":0.8088,\"参数三\":2.9169,\"参数二\":0.6541,\"参数五\":0.6229,\"参数四\":5.5326,\"时间\":\"2022/6/3013:09\"},\t{\"参数一\":0.9088,\"参数三\":2.7169,\"参数二\":0.0541,\"参数五\":0.4229,\"参数四\":3.5326,\"时间\":\"2022/6/3013:10\"}]}");
         // udp客户端,向服务端发送获取数据请求服务
-        udpClient.bind("127.0.0.1", 19000, Message.msgToBytes(message), "JC01");
+        udpClient.bind("127.0.0.1", 19000, Message.msgToBytes(message), "JC02");
         return CommonResult.buildSuccess();
     }
 }

+ 36 - 0
PHM-admin/phm-netty/src/main/java/com/phm/netty/service/impl/ProcessService.java

@@ -1,5 +1,6 @@
 package com.phm.netty.service.impl;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import org.springframework.beans.factory.annotation.Autowired;
@@ -23,7 +24,9 @@ import com.phm.netty.enums.OrderEnum;
 import com.phm.netty.service.IProcessService;
 import com.phm.system.service.ISysDictTypeService;
 
+import cn.hutool.core.lang.Console;
 import cn.hutool.core.util.IdUtil;
+import cn.hutool.json.JSONArray;
 import cn.hutool.json.JSONObject;
 import cn.hutool.json.JSONUtil;
 import lombok.extern.slf4j.Slf4j;
@@ -133,4 +136,37 @@ public class ProcessService implements IProcessService {
 
         return null;
     }
+
+    public static void main(String[] args) {
+        List<String> ss = new ArrayList<>();
+        ss.add("参数一");
+        JSONArray jsonArray = CsvUtils.getCsvDataByHeaders("D:\\phm\\dataPath\\csv" +
+                "\\parameterData\\JC02" + ".csv", ss);
+        // 打印JSON数组对象
+        Console.log(jsonArray);
+        // System.out.println(jsonArray.toString());
+        // int numberOfRandomNumbers = 10000;
+        // double minValue = 0.0000;
+        // double maxValue = 1.9999;
+        //
+        // Random random = new Random();
+        //
+        // for (int i = 0; i < numberOfRandomNumbers; i++) {
+        // double randomValue = minValue + (maxValue - minValue) * random.nextDouble();
+        // System.out.printf("%.4f%n", randomValue);
+        // }
+        // int numberOfDataPoints = 2000;
+        // String pattern = "yyyy/MM/dd HH:mm:ss";
+        // String startTime = "2023/11/20 13:08:02";
+        //
+        // DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
+        // LocalDateTime currentTime = LocalDateTime.parse(startTime, formatter);
+        //
+        // for (int i = 0; i < numberOfDataPoints; i++) {
+        // for (int i1 = 0; i1 < 5; i1++) {
+        // System.out.println(formatter.format(currentTime));
+        // }
+        // currentTime = currentTime.plusSeconds(1);
+        // }
+    }
 }