最近在做一个大屏监控,要实现的效果为:根据每个车间的PLC设备IP,去采集车间PLC设备的连接状态。
当初看到这个需求的时候,首先就想到在服务器上执行批处理脚本,将每个车间IP的ping结果写入txt文本里面,然后再用java去读取txt,将结果推送到前台。但是经过测试,当ip数量变多或ip都ping不通的情况下,批处理耗时太久,所以采用了多线程去处理这个ip的ping操作,在此记录下过程。
过程
- 定义车间IP
// GA-PLC map
public static final Map<String, String> gaPlcMap = Collections.unmodifiableMap(new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
put("AT", "192.168.x.xx"); // AT线
put("AC", "192.168.x.xx"); // AC线
put("AF", "192.168.x.xx"); // AF线
put("AD", "192.168.x.xx"); // AD线
put("AIP", "192.168.x.xx"); // AIP线
......
}
});
- 获取IP执行ping操作
//获取IP列表
List<PlcTemplete> ipList = map.entrySet()
.stream()
.map(e -> new PlcTemplete(e.getKey(), e.getValue(), false))
.collect(Collectors.toList());
if(CollectionUtils.isNotEmpty(ipList)) {
AtomicInteger count = new AtomicInteger(0);
int THREAD_COUNTS = ipList.size();
CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNTS);
Thread[] threads = new Thread[THREAD_COUNTS];
//开始ping
for(int i = 0; i < THREAD_COUNTS; i++) {
PlcTemplete plcTemplete = ipList.get(i);
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
try {
boolean pingSuccess = PingUtils.ping(plcTemplete.getIp(), 3, 2000);
plcTemplete.setSuccess(pingSuccess);
countDownLatch.countDown();
count.getAndIncrement();
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
});
threads[i].start();
}
try {
countDownLatch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
logger.error(e1.getMessage());
}
Map<String, Object> resultMap = ipList.stream().collect(
Collectors.toMap(PlcTemplete::getPline, plc -> plc));
wsMap.put("destination", destination);
wsMap.put("plcInfo", resultMap);
String message = StringEscapeUtils.unescapeJava(JSONObject.toJSON(wsMap).toString());
logger.info("PLC INFO {}:" + message);
// 发送websocket消息
webSocketServer.sendInfo(message, null);
}
- PingUtils
public class PingUtils {
private static Logger logger = LoggerFactory.getLogger(PingUtils.class);
/**
* @param ipAddress ip地址
* @param pingTimes 次数(一次ping,对方返回的ping的结果的次数)
* @param timeOut 超时时间 单位ms(ping不通,设置的此次ping结束时间)
* @return
*/
public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
BufferedReader in = null;
String pingCommand = null;
Runtime r = Runtime.getRuntime();
String osName = System.getProperty("os.name");
logger.info("项目所在系统是:" + osName);
if (osName.contains("Windows")) {
// 将要执行的ping命令,此命令是windows格式的命令
pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
} else {
// 将要执行的ping命令,此命令是Linux格式的命令
// -c:次数,-w:超时时间(单位/ms) ping -c 10 -w 0.5 192.168.120.206
pingCommand = "ping " + " -c " + "4" + " -w " + "2 " + ipAddress;
}
try {
// 执行命令并获取输出
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line, osName);
}
// 如果出现类似=23 ms ttl=64(TTL=64 Windows)这样的字样,出现的次数=测试次数则返回真
// return connectedCount == pingTimes;
logger.info("ping通设备IP[" + ipAddress + "]的次数为:" + connectedCount);
return connectedCount >= 2 ? true : false;
} catch (Exception ex) {
ex.printStackTrace(); // 出现异常则返回假
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 若line含有=18 ms ttl=64字样,说明已经ping通,返回1,否則返回0.
private static int getCheckResult(String line, String osName) {
if (osName.contains("Windows")) {
if (line.contains("TTL=")) {
return 1;
}
} else {
if (line.contains("ttl=")) {
return 1;
}
}
return 0;
}
public static void main(String[] args) {
String ipAddress = "127.0.0.1";
String osName = System.getProperty("os.name");
boolean ping = ping(ipAddress, 3, 3);
System.out.println(ping);
}
}