Browse Source

Merge branch 'master' of http://git.aseanbusiness.cn/qzyReal/gather-server

# Conflicts:
#	src/main/java/com/gzlh/background/client/BackgroundClientNetty.java
#	src/main/java/com/gzlh/startup/StartupRunner.java
qzyReal 1 year ago
parent
commit
3edfc85607

+ 44 - 39
src/main/java/com/gzlh/background/client/BackgroundClientHandler.java

@@ -1,61 +1,50 @@
 package com.gzlh.background.client;
 
-import com.gzlh.background.client.CustomHeartbeatHandler;
+import cn.hutool.json.JSONUtil;
+import com.gzlh.background.properties.BackgroundPropertiesConfig;
+import com.gzlh.event.EventBus;
+import com.gzlh.utils.DeviceCache;
 import io.netty.channel.ChannelHandler;
 import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
 import io.netty.handler.timeout.IdleStateEvent;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.Map;
 
 @Slf4j
 @ChannelHandler.Sharable
-public class BackgroundClientHandler extends CustomHeartbeatHandler {
+public class BackgroundClientHandler extends SimpleChannelInboundHandler<String> {
+
     private BackgroundClientNetty client;
 
+    @Resource
+    private EventBus eventBus;
+
+
     public BackgroundClientHandler(BackgroundClientNetty client) {
-        super("client");
         this.client = client;
     }
 
-
-//    @Override
-//    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
-//        System.out.println(1111);
-//        System.out.println("Client received: " + msg);
-//
-//    }
-
-
-    //    @Override
-//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
-//        System.out.println(1111);
-//        System.out.println(msg);
-////        ByteBuf in = (ByteBuf) msg;
-////        System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8));
-//
-//    }
-
     @Override
-    protected void handleData(ChannelHandlerContext channelHandlerContext, String msg) {
-//        byte[] data = new byte[byteBuf.readableBytes() - 5];
-//        byteBuf.skipBytes(5);
-//        byteBuf.readBytes(data);
-//        String content = new String(data);
-        System.out.println(name + " get content: " + msg);
+    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
+//        System.out.println("Client received: " + msg);
+        if (!"Heartbeat".equalsIgnoreCase(msg)){
+            eventBus.start(msg);
+        }
     }
 
-    @Override
-    protected void handleAllIdle(ChannelHandlerContext ctx) {
-        super.handleAllIdle(ctx);
-        sendPingMsg(ctx);
-    }
 
+    protected void sendHeartbeat(ChannelHandlerContext context) {
+//        向后台发送设备信息json字符串
+        String jsonStr = JSONUtil.toJsonStr(DeviceCache.getCacheMap());
+        context.writeAndFlush(jsonStr);
+//        System.out.println(" sent ping msg to " + context.channel().remoteAddress());
+    }
 
-//    @Override
-//    public void channelActive(ChannelHandlerContext ctx) throws Exception {
-//        //当被通知Channel是活跃的时候,发送一条消息
-////        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
-////        sendPingMsg(ctx);
-//    }
 
     @Override
     public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
@@ -78,6 +67,21 @@ public class BackgroundClientHandler extends CustomHeartbeatHandler {
         }
     }
 
+    protected void handleReaderIdle(ChannelHandlerContext ctx) {
+//        System.err.println("---READER_IDLE---");
+    }
+
+    protected void handleWriterIdle(ChannelHandlerContext ctx) {
+        //写空闲时发送心跳包
+        sendHeartbeat(ctx);
+//        System.err.println("---WRITER_IDLE---");
+    }
+
+    protected void handleAllIdle(ChannelHandlerContext ctx) {
+        System.err.println("---ALL_IDLE---");
+//        sendHeartbeat(ctx);
+    }
+
 
     @Override
     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
@@ -87,7 +91,8 @@ public class BackgroundClientHandler extends CustomHeartbeatHandler {
 
     @Override
     public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-        super.channelInactive(ctx);
+        log.error("-------------后端服务器连接断开,{}-----------,进行重连", ctx.channel().remoteAddress());
+//        System.err.println("---后端服务器连接断开," + ctx.channel().remoteAddress() + " ---");
         client.connect();
     }
 

+ 6 - 2
src/main/java/com/gzlh/background/client/BackgroundClientNetty.java

@@ -1,6 +1,8 @@
 package com.gzlh.background.client;
 
 import com.gzlh.background.properties.BackgroundPropertiesConfig;
+import com.gzlh.led.properties.LedPropertiesConfig;
+import com.gzlh.utils.DeviceCache;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.channel.*;
 import io.netty.channel.nio.NioEventLoopGroup;
@@ -11,6 +13,7 @@ import io.netty.handler.codec.string.StringEncoder;
 import io.netty.handler.timeout.IdleStateHandler;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
@@ -31,6 +34,7 @@ public class BackgroundClientNetty {
 
     @Bean("backgroundClient")
     public Bootstrap bootstrap() {
+
         EventLoopGroup group = new NioEventLoopGroup();
         bootstrap = new Bootstrap();
         return bootstrap.group(group)
@@ -42,7 +46,7 @@ public class BackgroundClientNetty {
                         socketChannel.pipeline()
                                 .addLast("decoder", new StringDecoder())
                                 .addLast("encoder", new StringEncoder())
-                                .addLast(new IdleStateHandler(0, 0, 5))
+                                .addLast(new IdleStateHandler(0, 5, 0))
                                 .addLast(backgroundClientHandler);
                     }
                 });
@@ -61,7 +65,7 @@ public class BackgroundClientNetty {
                 channel = future1.channel();
                 log.info("后端服务器连接成功,{},{}",config.getHost(), config.getPort());
             } else {
-                log.error("------------后端-连接服务器失败,{},{}-----------,进行重连",config.getHost(), config.getPort());
+                log.error("-------------后端连接服务器失败,{},{}-----------,进行重连",config.getHost(), config.getPort());
                 future1.channel().eventLoop().schedule(this::connect, 5, TimeUnit.SECONDS);
             }
         });

+ 0 - 91
src/main/java/com/gzlh/background/client/CustomHeartbeatHandler.java

@@ -1,91 +0,0 @@
-package com.gzlh.background.client;
-
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import io.netty.handler.timeout.IdleStateEvent;
-
-public abstract class CustomHeartbeatHandler extends SimpleChannelInboundHandler<String> {
-    public static final byte PING_MSG = 1;
-    public static final byte PONG_MSG = 2;
-    public static final byte CUSTOM_MSG = 3;
-    protected String name;
-    private int heartbeatCount = 0;
-
-    public CustomHeartbeatHandler(String name) {
-        this.name = name;
-    }
-
-    @Override
-    protected void channelRead0(ChannelHandlerContext context, String msg) throws Exception {
-//        if (byteBuf.getByte(4) == PING_MSG) {
-//            sendPongMsg(context);
-//        } else if (byteBuf.getByte(4) == PONG_MSG){
-//            System.out.println(name + " get pong msg from " + context.channel().remoteAddress());
-//        } else {
-            handleData(context, msg);
-//        }
-    }
-
-    protected void sendPingMsg(ChannelHandlerContext context) {
-//        ByteBuf buf = context.alloc().buffer(5);
-//        buf.writeInt(5);
-//        buf.writeByte(PING_MSG);
-        context.writeAndFlush("ping");
-        heartbeatCount++;
-        System.out.println(name + " sent ping msg to " + context.channel().remoteAddress() + ", count: " + heartbeatCount);
-    }
-
-    protected void sendPongMsg(ChannelHandlerContext context) {
-//        ByteBuf buf = context.alloc().buffer(5);
-//        buf.writeInt(5);
-//        buf.writeByte(PONG_MSG);
-        context.channel().writeAndFlush("pong");
-        heartbeatCount++;
-        System.out.println(name + " sent pong msg to " + context.channel().remoteAddress() + ", count: " + heartbeatCount);
-    }
-
-    protected abstract void handleData(ChannelHandlerContext channelHandlerContext, String msg);
-
-    @Override
-    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
-        // IdleStateHandler 所产生的 IdleStateEvent 的处理逻辑.
-        if (evt instanceof IdleStateEvent) {
-            IdleStateEvent e = (IdleStateEvent) evt;
-            switch (e.state()) {
-                case READER_IDLE:
-                    handleReaderIdle(ctx);
-                    break;
-                case WRITER_IDLE:
-                    handleWriterIdle(ctx);
-                    break;
-                case ALL_IDLE:
-                    handleAllIdle(ctx);
-                    break;
-                default:
-                    break;
-            }
-        }
-    }
-
-    @Override
-    public void channelActive(ChannelHandlerContext ctx) throws Exception {
-        System.err.println("---" + ctx.channel().remoteAddress() + " is active---");
-    }
-
-    @Override
-    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-        System.err.println("---" + ctx.channel().remoteAddress() + " is inactive---");
-    }
-
-    protected void handleReaderIdle(ChannelHandlerContext ctx) {
-        System.err.println("---READER_IDLE---");
-    }
-
-    protected void handleWriterIdle(ChannelHandlerContext ctx) {
-        System.err.println("---WRITER_IDLE---");
-    }
-
-    protected void handleAllIdle(ChannelHandlerContext ctx) {
-        System.err.println("---ALL_IDLE---");
-    }
-}

+ 5 - 0
src/main/java/com/gzlh/startup/StartupRunner.java

@@ -18,6 +18,7 @@ import com.gzlh.device.led.client.LedNettyConfig;
 import com.gzlh.device.infrared.client.RedNettyConfig;
 import com.gzlh.device.weighbridge.client.WeighbridgeNettyConfig;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.CommandLineRunner;
 import org.springframework.stereotype.Component;
 
@@ -42,6 +43,8 @@ public class StartupRunner implements CommandLineRunner {
     private BackgroundPropertiesConfig backgroundPropertiesConfig;
     @Resource
     private BackgroundClientNetty backgroundClientNetty;
+    @Value("${application.channel-code}")
+    private String channelCode;
 
     @Resource
     private HkUtils hkUtils;
@@ -92,5 +95,7 @@ public class StartupRunner implements CommandLineRunner {
         JSONObject result = XML.toJSONObject(content);
         ApplicationConfigDTO configDTO = result.toBean(ApplicationConfigDTO.class);
         eventBus.setEventDTOList(configDTO.getConfig().getEventList().getEvent());
+
+        DeviceCache.add("channelCode",channelCode);
     }
 }

+ 25 - 0
src/main/java/com/gzlh/utils/DeviceCache.java

@@ -0,0 +1,25 @@
+package com.gzlh.utils;
+
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class DeviceCache {
+    private static Map<String,String> map = new ConcurrentHashMap<String,String>();
+
+    public static void add(String k,String v){
+        map.put(k,v);
+    }
+
+    public static String get(String k){
+        return map.get(k);
+    }
+
+    public static String remove(String k){
+        return map.remove(k);
+    }
+
+    public static Map<String,String> getCacheMap(){
+        return map;
+    }
+}

+ 1 - 1
src/main/resources/application.yml

@@ -3,7 +3,7 @@ server:
 application:
   server-url: http://127.0.0.1:8099/pro #后端服务器地址
   channel-name: "A1园内地磅通道"
-  channel-code:
+  channel-code: "A1001"
 #地磅配置
 weighbridge:
   host: 127.0.0.1