瀏覽代碼

tcp连接添加重试

zhifei 1 年之前
父節點
當前提交
723b171ea0

+ 1 - 1
pom.xml

@@ -43,7 +43,7 @@
         <knife4j.spring.version>3.0.3</knife4j.spring.version>
         <knife4j.spring.version>3.0.3</knife4j.spring.version>
         <guava.version>23.0</guava.version>
         <guava.version>23.0</guava.version>
         <guava.retry.version>2.0.0</guava.retry.version>
         <guava.retry.version>2.0.0</guava.retry.version>
-        <HslCommunication.version>2.0.2</HslCommunication.version>
+        <HslCommunication.version>3.6.0</HslCommunication.version>
     </properties>
     </properties>
 
 
     <!-- 依赖声明 -->
     <!-- 依赖声明 -->

+ 6 - 3
warewms-admin/src/main/resources/application.yml

@@ -14,16 +14,19 @@ plc:
     rack: 0
     rack: 0
     name: ChengZhongPlc
     name: ChengZhongPlc
     siemensPLCS: S1200
     siemensPLCS: S1200
+    heartbeat: DB11.0.0
   plcList[1]:
   plcList[1]:
-    ip: 172.20.52.22
+    ip: 172.20.27.2
     enable: false
     enable: false
-    name: XiMianPlc
-    siemensPLCS: S1500
+    name: DaoJiaoJiPlc
+    siemensPLCS: S200Smart
+    heartbeat:
   plcList[2]:
   plcList[2]:
     ip: 172.20.52.24
     ip: 172.20.52.24
     enable: false
     enable: false
     name: ZaZhiPlc
     name: ZaZhiPlc
     siemensPLCS: S1500
     siemensPLCS: S1500
+    heartbeat:
 
 
 MES:
 MES:
   address: http://192.20.2.4:9090
   address: http://192.20.2.4:9090

+ 54 - 10
warewms-system/src/main/java/com/warewms/hailiang/connect/InkjetPrintersConnect.java

@@ -1,15 +1,20 @@
 package com.warewms.hailiang.connect;
 package com.warewms.hailiang.connect;
 
 
+import com.github.rholder.retry.*;
 import com.warewms.hailiang.connect.handler.InkjetPrintersHandler;
 import com.warewms.hailiang.connect.handler.InkjetPrintersHandler;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.EventLoopGroup;
+import io.netty.channel.*;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.channel.socket.nio.NioSocketChannel;
 import io.netty.channel.socket.nio.NioSocketChannel;
+import lombok.CustomLog;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Component;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 
 /**
 /**
  * Created with IntelliJ IDEA.
  * Created with IntelliJ IDEA.
@@ -33,6 +38,8 @@ public class InkjetPrintersConnect implements TCPConnectBase {
 
 
     private EventLoopGroup group;
     private EventLoopGroup group;
 
 
+
+
     @Override
     @Override
     public void init() throws InterruptedException {
     public void init() throws InterruptedException {
         log.info("喷码机正在进行连接");
         log.info("喷码机正在进行连接");
@@ -47,14 +54,51 @@ public class InkjetPrintersConnect implements TCPConnectBase {
                             socketChannel.pipeline().addLast(new InkjetPrintersHandler());
                             socketChannel.pipeline().addLast(new InkjetPrintersHandler());
                         }
                         }
                     });
                     });
-            //发起异步连接操作
             future = bootstrap.connect(IP_ADDR, PORT).sync();
             future = bootstrap.connect(IP_ADDR, PORT).sync();
-            future.channel().closeFuture().sync();
-            bootstrap.clone();
-        } finally {
-            group.shutdownGracefully();
+            future.addListener((channelFuture) -> {
+                if (channelFuture.isSuccess()) {
+                    log.info("喷码机连接成功");
+                }else {
+                    log.info("连接失败等待重试!");
+                    retry();
+                }
+            });
+        } catch (Exception e) {
+            log.error("喷码设备连接异常,{},准备重试", e.getMessage());
+            retry();
+        }
+    }
+
+    @Override
+    public void retry() {
+        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
+                .retryIfResult(Boolean.FALSE::equals)
+                .retryIfExceptionOfType(Exception.class)
+                .withStopStrategy(StopStrategies.neverStop())
+                .withWaitStrategy(WaitStrategies.fixedWait(5, TimeUnit.SECONDS))
+                .build();
+        try {
+            retryer.call(new Callable<Boolean>() {
+                AtomicBoolean isSuccess = new AtomicBoolean(false);
+                @Override
+                public Boolean call() throws Exception {
+                    log.info("喷码机连接重试");
+                    future = bootstrap.connect(IP_ADDR, PORT).sync();
+                    future.addListener((channelFuture) -> {
+                        isSuccess.set(channelFuture.isSuccess());
+                        if (channelFuture.isSuccess()) {
+                            log.info("喷码机连接成功");
+                        }else {
+                            log.info("连接失败等待重试!");
+                        }
+                    });
+                    Thread.sleep(3000);
+                    return isSuccess.get();
+                }
+            });
+        } catch (RetryException | ExecutionException e) {
+            e.printStackTrace();
         }
         }
-        log.info("喷码机连接成功");
     }
     }
 
 
     @Override
     @Override

+ 4 - 0
warewms-system/src/main/java/com/warewms/hailiang/connect/TCPConnectBase.java

@@ -11,9 +11,13 @@ import java.io.IOException;
  * To change this template use File | Settings | File Templates.
  * To change this template use File | Settings | File Templates.
  * Description:TCP连接基类
  * Description:TCP连接基类
  **/
  **/
+
 public interface TCPConnectBase {
 public interface TCPConnectBase {
 
 
     void init() throws IOException, InterruptedException;
     void init() throws IOException, InterruptedException;
 
 
+    void retry() throws InterruptedException;
+
     void close();
     void close();
+
 }
 }

+ 15 - 0
warewms-system/src/main/java/com/warewms/hailiang/connect/handler/InkjetPrintersHandler.java

@@ -1,6 +1,8 @@
 package com.warewms.hailiang.connect.handler;
 package com.warewms.hailiang.connect.handler;
 
 
 import com.warewms.common.annotation.Log;
 import com.warewms.common.annotation.Log;
+import com.warewms.hailiang.connect.InkjetPrintersConnect;
+import com.warewms.hailiang.init.TcpServiceRunner;
 import com.warewms.hailiang.util.ParseMsgTools;
 import com.warewms.hailiang.util.ParseMsgTools;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import io.netty.buffer.Unpooled;
@@ -8,6 +10,10 @@ import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInboundHandlerAdapter;
 import io.netty.channel.ChannelInboundHandlerAdapter;
 import io.netty.util.CharsetUtil;
 import io.netty.util.CharsetUtil;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.Resource;
 
 
 /**
 /**
  * Created with IntelliJ IDEA.
  * Created with IntelliJ IDEA.
@@ -19,8 +25,10 @@ import lombok.extern.slf4j.Slf4j;
  * Description: 喷码机连接消息处理类
  * Description: 喷码机连接消息处理类
  **/
  **/
 @Slf4j
 @Slf4j
+@Component
 public class InkjetPrintersHandler extends ChannelInboundHandlerAdapter  {
 public class InkjetPrintersHandler extends ChannelInboundHandlerAdapter  {
 
 
+
     @Override
     @Override
     public void channelActive(ChannelHandlerContext ctx) throws Exception {
     public void channelActive(ChannelHandlerContext ctx) throws Exception {
 //        ParseMsgTools.StringTohexString("23071115000");
 //        ParseMsgTools.StringTohexString("23071115000");
@@ -33,4 +41,11 @@ public class InkjetPrintersHandler extends ChannelInboundHandlerAdapter  {
         log.info(String.valueOf(byteBuf.toString(CharsetUtil.UTF_8)));
         log.info(String.valueOf(byteBuf.toString(CharsetUtil.UTF_8)));
     }
     }
 
 
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+        log.error("喷码机连接已断开!");
+        InkjetPrintersConnect inkjetPrintersConnect = (InkjetPrintersConnect) TcpServiceRunner.getTCPInstanceList().get("InkjetPrintersConnect");
+        inkjetPrintersConnect.retry();
+        super.channelInactive(ctx);
+    }
 }
 }

+ 13 - 7
warewms-system/src/main/java/com/warewms/hailiang/init/TcpServiceRunner.java

@@ -9,10 +9,9 @@ import org.springframework.core.annotation.Order;
 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 
 
-import javax.xml.ws.soap.Addressing;
 import java.io.IOException;
 import java.io.IOException;
-import java.lang.reflect.Modifier;
-import java.util.*;
+import java.util.HashMap;
+import java.util.Set;
 
 
 /**
 /**
  * Created with IntelliJ IDEA.
  * Created with IntelliJ IDEA.
@@ -31,18 +30,23 @@ public class TcpServiceRunner implements CommandLineRunner {
 
 
     @Autowired
     @Autowired
     ThreadPoolTaskExecutor threadPoolTaskExecutor;
     ThreadPoolTaskExecutor threadPoolTaskExecutor;
+
+    private static HashMap<String,TCPConnectBase> TCPInstanceList = new HashMap<>();
+
     @Override
     @Override
     public void run(String... args) throws Exception {
     public void run(String... args) throws Exception {
         Set<Class<?>> classes = ClassUtil.scanPackageBySuper("com.warewms.hailiang.connect", TCPConnectBase.class);
         Set<Class<?>> classes = ClassUtil.scanPackageBySuper("com.warewms.hailiang.connect", TCPConnectBase.class);
         for (Class<?> aClass : classes) {
         for (Class<?> aClass : classes) {
             Object o = aClass.newInstance();
             Object o = aClass.newInstance();
             if (o instanceof TCPConnectBase) {
             if (o instanceof TCPConnectBase) {
-                TCPConnectBase nodeRedModel = (TCPConnectBase) o;
+                TCPConnectBase nodeModel = (TCPConnectBase) o;
                 threadPoolTaskExecutor.execute(() -> {
                 threadPoolTaskExecutor.execute(() -> {
                     try {
                     try {
-                        nodeRedModel.init();
+                        nodeModel.init();
+                        System.out.println(aClass.getSimpleName());
+                        TCPInstanceList.put(aClass.getSimpleName(),nodeModel);
                     } catch (IOException e) {
                     } catch (IOException e) {
-                        nodeRedModel.close();
+                        nodeModel.close();
                         throw new RuntimeException(e);
                         throw new RuntimeException(e);
                     } catch (InterruptedException e) {
                     } catch (InterruptedException e) {
                         throw new RuntimeException(e);
                         throw new RuntimeException(e);
@@ -50,7 +54,9 @@ public class TcpServiceRunner implements CommandLineRunner {
                 });
                 });
             }
             }
         }
         }
-
     }
     }
 
 
+    public static HashMap getTCPInstanceList(){
+        return TCPInstanceList;
+    }
 }
 }