fix:线程阻塞问题处理8-19

This commit is contained in:
2024-08-19 15:57:05 +08:00
parent cc507c307b
commit 4512ea7f83
21 changed files with 70 additions and 205 deletions

View File

@@ -1,6 +1,5 @@
package org.nl.acs.auto.run;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
@@ -11,8 +10,6 @@ import org.nl.acs.device.service.DeviceService;
import org.nl.acs.device_driver.agv.ndcone.AgvNdcOneDeviceDriver;
import org.nl.acs.device_driver.agv.ndctwo.AgvNdcTwoDeviceDriver;
import org.nl.acs.device_driver.autodoor.standard_autodoor.StandardAutodoorDeviceDriver;
import org.nl.acs.device_driver.conveyor.standard_inspect_site.StandardInspectSiteDeviceDriver;
import org.nl.acs.device_driver.two_conveyor.oven_manipulator.OvenGantryManipulatorDeviceDriver;
import org.nl.acs.ext.wms.service.AcsToWmsService;
import org.nl.acs.ext.wms.service.impl.AcsToWmsServiceImpl;
import org.nl.acs.instruction.domain.Instruction;
@@ -22,7 +19,6 @@ import org.nl.acs.log.service.DeviceExecuteLogService;
import org.nl.acs.opc.DeviceAppService;
import org.nl.config.SpringContextHolder;
import org.nl.config.lucene.service.LuceneExecuteLogService;
import org.nl.config.lucene.service.dto.LuceneLogDto;
import org.nl.system.service.param.ISysParamService;
import org.nl.system.service.param.impl.SysParamServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
@@ -31,13 +27,9 @@ import org.springframework.stereotype.Component;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.nl.acs.agv.server.impl.NDCAgvServiceImpl.Bytes2HexString;
@@ -46,7 +38,7 @@ import static org.nl.acs.agv.server.impl.NDCAgvServiceImpl.Bytes2HexString;
@Component
public class TwoNDCSocketConnectionAutoRun extends AbstractAutoRunnable {
Socket s;
Socket socket;
String ip = "192.168.46.225";
int port = 1234;
static DataOutputStream dos;
@@ -111,20 +103,20 @@ public class TwoNDCSocketConnectionAutoRun extends AbstractAutoRunnable {
InetSocketAddress socketAddress = new InetSocketAddress(ip, port);
byte[] b = new byte[1024];
s = new Socket();
s.connect(socketAddress, 2 * 1000);
s.setKeepAlive(true);//长链接
socket = new Socket();
socket.connect(socketAddress, 2 * 1000);
socket.setKeepAlive(true);//长链接
// s.setSoTimeout(1000* 60 * 10);//读取超时时间
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
while (bConnected) {
int count = dis.read(b);
if (count == -1) {
log.error("agv连接出现异常:服务端被关闭");
if (ObjectUtil.isNotEmpty(s)) {
s.close();
if (ObjectUtil.isNotEmpty(socket)) {
socket.close();
}
break;
}
@@ -321,27 +313,17 @@ public class TwoNDCSocketConnectionAutoRun extends AbstractAutoRunnable {
}
}
} catch (Exception e) {
System.out.println("TwoAgv链接异常");
log.info("TwoAgv链接异常");
log.error("agv连接出现异常:{}", e);
LuceneLogDto logDto = LuceneLogDto.builder()
.device_code("agv连接出现异常")
.content("agv异常" + e.getMessage())
.build();
logDto.setLog_level(4);
luceneExecuteLogService.deviceExecuteLog(logDto);
logServer.deviceExecuteLog("NDC2", "", "", "agv异常" + e.getMessage());
logServer.deviceExecuteLog("NDC2", "", "", "agv异常" + e);
if (ObjectUtil.isNotEmpty(s)) {
s.close();
if (ObjectUtil.isNotEmpty(socket)) {
socket.close();
}
System.out.println(e.getMessage());
} finally {
closeResources();
}
}
@@ -350,10 +332,17 @@ public class TwoNDCSocketConnectionAutoRun extends AbstractAutoRunnable {
@Override
public void stop() {
super.after();
closeResources();
}
private void closeResources() {
try {
s.close();
} catch (Exception e) {
e.printStackTrace();
if (dis != null) dis.close();
if (dos != null) dos.close();
if (socket != null && !socket.isClosed()) socket.close();
} catch (IOException e) {
log.error("关闭资源时发生错误: {}", e.getMessage(), e);
}
}

View File

@@ -257,7 +257,14 @@ public class BeltConveyorDeviceDriver extends AbstractOpcDeviceDriver implements
});
}
//申请空托盘出库
if (mode == 8 && !requireSucess) {
// if (mode == 8 && !requireSucess) {
if (true) {
List list = new ArrayList<>();
Map map = new HashMap<>();
map.put("code", "to_target");
map.put("value", "0");
list.add(map);
this.writing(list);
if (container_type == 0) {
message = "托盘类型为空";
} else {
@@ -765,11 +772,6 @@ public class BeltConveyorDeviceDriver extends AbstractOpcDeviceDriver implements
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -1,5 +1,6 @@
package org.nl.acs.device_driver.driver;
import lombok.extern.slf4j.Slf4j;
import org.nl.acs.opc.*;
import org.nl.acs.udw.UnifiedDataAccessor;
import org.nl.acs.udw.UnifiedDataAccessorFactory;
@@ -12,6 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
@Slf4j
public class AbstractOpcDeviceDriver extends AbstractDeviceDriver implements OpcDeviceDriver {
UnifiedDataAccessor opcUdw;
@@ -116,8 +118,8 @@ public class AbstractOpcDeviceDriver extends AbstractDeviceDriver implements Opc
ThreadUtl.sleep(100L);
}
if (i >= 3) {
// log.info("写入次数超过3次而失败");
if (i >= 2) {
log.info("写入次数超过3次而失败");
throw new RuntimeException("写入次数超过3次而失败");
}
++i;

View File

@@ -716,11 +716,6 @@ public class BoxStorageOutConveyorDeviceDriver extends AbstractOpcDeviceDriver i
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -533,11 +533,6 @@ public class BoxSubvolumesConveyorDeviceDriver extends AbstractOpcDeviceDriver i
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -757,11 +757,7 @@ public class FinishedProductOutBindLableDeviceDriver extends AbstractOpcDeviceDr
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -594,11 +594,6 @@ public class FoldDiscSiteDeviceDriver extends AbstractOpcDeviceDriver implements
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -1070,11 +1070,6 @@ public class ConveyorWithScannerWeightDeviceDriver extends AbstractOpcDeviceDriv
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -482,11 +482,6 @@ public class UnBoxLableConveyorDeviceDriver extends AbstractOpcDeviceDriver impl
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -583,11 +583,6 @@ public class BoxPackageManipulatorDeviceDriver extends AbstractOpcDeviceDriver i
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -529,11 +529,6 @@ public class BoxStorageManipulatorDeviceDriver extends AbstractOpcDeviceDriver i
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -547,11 +547,6 @@ public class ReturnGoodManipulatorDeviceDriver extends AbstractOpcDeviceDriver i
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -607,11 +607,6 @@ public class TrappedManipulatorManipulatorDeviceDriver extends AbstractOpcDevice
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -642,11 +642,6 @@ public class VolumeTwoManipulatorManipulatorDeviceDriver extends AbstractOpcDevi
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -1391,11 +1391,6 @@ public class StandardStackerDeviceDriver extends AbstractOpcDeviceDriver impleme
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -201,11 +201,6 @@ public class ManipulatorAgvStationDeviceDriver extends AbstractOpcDeviceDriver i
this.checkcontrol(itemMap);
} catch (Exception e) {
e.printStackTrace();
try {
this.checkcontrol(itemMap);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}

View File

@@ -2,22 +2,21 @@ package org.nl.acs.opc;
import lombok.extern.slf4j.Slf4j;
import org.dromara.dynamictp.core.DtpRegistry;
import org.dromara.dynamictp.core.executor.DtpExecutor;
import org.dromara.dynamictp.core.support.ExecutorWrapper;
import org.nl.acs.auto.run.AbstractAutoRunnable;
import org.nl.acs.auto.run.AutoRunService;
import org.nl.acs.device_driver.driver.ExecutableDeviceDriver;
import org.nl.acs.instruction.service.InstructionService;
import org.nl.acs.udw.UnifiedDataAccessor;
import org.nl.acs.udw.UnifiedDataAccessorFactory;
import org.nl.config.SpringContextHolder;
import org.nl.config.thread.TheadFactoryName;
import org.nl.config.thread.ThreadPoolExecutorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import picocli.CommandLine;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
@@ -38,10 +37,6 @@ public class DeviceExecuteAutoRun extends AbstractAutoRunnable {
int loop_time_millions = 100;
@Resource
private ThreadPoolExecutor executorService;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(30);
Map<String, BlockedRunable> runs;
@@ -98,7 +93,7 @@ public class DeviceExecuteAutoRun extends AbstractAutoRunnable {
Thread.sleep(1000L);
if (i > 60) {
UnifiedDataAccessor accessor_value = UnifiedDataAccessorFactory.getAccessor(OpcConfig.udw_opc_value_key);
if(accessor_value.getAllKey().size() < 1){
if (accessor_value.getAllKey().size() < 1) {
autoRunService.startThread("DeviceOpcSynchronizeAutoRun");
}
log.info("设备执行线程放弃等待opc同步线程...");
@@ -122,32 +117,6 @@ public class DeviceExecuteAutoRun extends AbstractAutoRunnable {
@Override
public void subRun() throws Exception {
deviceDriver.executeAuto();
/* ThreadPoolExecutor executor= DtpRegistry.getDtpExecutor("dtpExecutor1");
Future<?> submit = executor.submit(() -> {
try {
deviceDriver.executeAuto();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
try {
// 设置超时时间为 15 秒,如果任务超时,抛出 TimeoutException
submit.get(10, TimeUnit.SECONDS);
System.out.println();
} catch (TimeoutException e) {
System.out.println("任务超时,取消任务!");
// 使用反射获取 FutureTask 中的线程,并使用 Thread.stop() 强制终止
Field runnerField = submit.getClass().getDeclaredField("runner");
runnerField.setAccessible(true);
Thread runnerThread = (Thread) runnerField.get(submit);
if (runnerThread != null) {
runnerThread.stop(); // 强制终止线程(不推荐)
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}*/
}
@Override
@@ -159,74 +128,23 @@ public class DeviceExecuteAutoRun extends AbstractAutoRunnable {
this.runs.put(deviceDriver.getDeviceCode(), runnable);
}
runnable.setIndex(this.runs);
// this.executorService.execute(runnable);
Future<?> future = this.executorService.submit(runnable);
/* try {
// 设置超时时间为 30 秒,如果任务超时,抛出 TimeoutException
future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("任务超时,取消任务!");
// 超时后取消任务,并设置为 true 以中断执行中的线程
future.cancel(true);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}*/
ExecutorService executorService = (ExecutorService) ThreadPoolExecutorUtil.getPoll();
Future<?> future = executorService.submit(runnable);
//plc断连后强制终止线程
/* try {
// 设置超时时间为 15 秒,如果任务超时,抛出 TimeoutException
future.get(15, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("任务超时,取消任务!");
// 使用反射获取 FutureTask 中的线程,并使用 Thread.stop() 强制终止
Field runnerField = future.getClass().getDeclaredField("runner");
runnerField.setAccessible(true);
Thread runnerThread = (Thread) runnerField.get(future);
if (runnerThread != null) {
runnerThread.stop(); // 强制终止线程(不推荐)
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}*/
// 使用调度器在超时后取消任务
ScheduledExecutorService scheduler = (ScheduledExecutorService) DtpRegistry.getExecutor("scheduled_pool");
// 使用调度器在超时后取消任务
scheduler.schedule(() -> {
if (!future.isDone()) {
// future.cancel(true); // 尝试中断任务
// Field runnerField = null;
// try {
// runnerField = future.getClass().getDeclaredField("runner");
// runnerField.setAccessible(true);
// Thread runnerThread = (Thread) runnerField.get(future);
// if (runnerThread != null) {
// runnerThread.stop(); // 强制终止线程(不推荐)
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
try {
// 设置超时时间为 30 秒,如果任务超时,抛出 TimeoutException
future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("任务超时,取消任务!");
// 超时后取消任务,并设置为 true 以中断执行中的线程
} catch (Exception e) {
future.cancel(true);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}, 5, TimeUnit.SECONDS); // 设置超时时间为10秒
}, 1, TimeUnit.MILLISECONDS); // 设置超时时间为10秒
}
}
}

View File

@@ -10,6 +10,7 @@ import org.jinterop.dcom.core.*;
import org.nl.acs.device_driver.driver.ItemValue;
import org.nl.common.exception.BadRequestException;
import org.nl.config.SpringContextHolder;
import org.nl.config.language.LangProcess;
import org.openscada.opc.lib.common.ConnectionInformation;
import org.openscada.opc.lib.da.*;
@@ -44,7 +45,6 @@ public class OpcUtl {
public static void writeValue(Group group, WriteRequest... requests) throws BadRequestException {
try {
Map<Item, Integer> e = null;
try {
e = group.write(requests);
// group.write(requests);

View File

@@ -35,7 +35,7 @@ public class ThreadPoolExecutorUtil {
public static Executor getPoll(){
return DtpRegistry.getExecutor("dtpExecutor1");
return DtpRegistry.getExecutor("cool_pool");
/* AsyncTaskProperties properties = SpringContextHolder.getBean(AsyncTaskProperties.class);
return new ThreadPoolExecutor(

View File

@@ -51,22 +51,40 @@ spring:
monitorInterval: 8
tomcatTp: # tomcat webserver 线程池配置
threadPoolAliasName: tomcat 线程池 # 线程池别名,可选
corePoolSize: 10
corePoolSize: 30
maximumPoolSize: 50
keepAliveTime: 60
runTimeout: 10000
queueTimeout: 100
executors: # 动态线程池配置,都有默认值,采用默认值的可以不配置该项,减少配置量
- threadPoolName: dtpExecutor1 # 线程池名称,必填
- threadPoolName: cool_pool # 线程池名称,必填dtpExecutor1
threadPoolAliasName: core_thread # 线程池别名,可选
executorType: common # 线程池类型 common、eager、ordered、scheduled、priority默认 common
corePoolSize: 10 # 核心线程数默认1
maximumPoolSize: 30 # 最大线程数默认cpu核数
corePoolSize: 30 # 核心线程数默认1
maximumPoolSize: 50 # 最大线程数默认cpu核数
queueCapacity: 1024 # 队列容量默认1024
queueType: VariableLinkedBlockingQueue # 任务队列查看源码QueueTypeEnum枚举类默认VariableLinkedBlockingQueue
rejectedHandlerType: CallerRunsPolicy # 拒绝策略查看RejectedTypeEnum枚举类默认AbortPolicy
keepAliveTime: 30 # 空闲线程等待超时时间默认60
threadNamePrefix: core_thread # 线程名前缀默认dtp
tryInterrupt: true
allowCoreThreadTimeOut: true # 是否允许核心线程池超时默认false
waitForTasksToCompleteOnShutdown: true # 参考spring线程池设计优雅关闭线程池默认true
awaitTerminationSeconds: 5 # 优雅关闭线程池时阻塞等待线程池中任务执行时间默认3单位s
preStartAllCoreThreads: false # 是否预热所有核心线程默认false
runTimeout: 2000 # 任务执行超时阈值单位ms默认0不统计
queueTimeout: 1000 # 任务在队列等待超时阈值单位ms默认0不统计
- threadPoolName: scheduled_pool # 线程池名称,必填
threadPoolAliasName: scheduled_thread # 线程池别名,可选
executorType: scheduled # 线程池类型 common、eager、ordered、scheduled、priority默认 common
corePoolSize: 30 # 核心线程数默认1
maximumPoolSize: 50 # 最大线程数默认cpu核数
queueCapacity: 1024 # 队列容量默认1024
queueType: VariableLinkedBlockingQueue # 任务队列查看源码QueueTypeEnum枚举类默认VariableLinkedBlockingQueue
rejectedHandlerType: CallerRunsPolicy # 拒绝策略查看RejectedTypeEnum枚举类默认AbortPolicy
keepAliveTime: 30 # 空闲线程等待超时时间默认60
threadNamePrefix: scheduled_thread # 线程名前缀默认dtp
tryInterrupt: true
allowCoreThreadTimeOut: true # 是否允许核心线程池超时默认false
waitForTasksToCompleteOnShutdown: true # 参考spring线程池设计优雅关闭线程池默认true
awaitTerminationSeconds: 5 # 优雅关闭线程池时阻塞等待线程池中任务执行时间默认3单位s

View File

@@ -12,7 +12,7 @@ https://juejin.cn/post/6844903775631572999
<contextName>nlAdmin</contextName>
<property name="log.charset" value="utf-8"/>
<property name="log.pattern"
value="%black(%contextName-) %red(%d{yyyy-MM-dd HH:mm:ss.SSS}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}) - %gray(%msg%n)"/>
value="%black(%contextName-) %red(%d{yyyy-MM-dd HH:mm:ss.SSS}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}) - %cyan(%msg%n)"/>
<springProperty scope="context" name="logPath" source="logging.file.path" defaultValue="logs"/>
<property name="SYSTEM_NAME" value="${systemName}"/>
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->