0
点赞
收藏
分享

微信扫一扫

java检测电脑是否在线

业务需要检测常用的电脑是否在线, 不在线给提醒;相关代码如下

由于多台设备,一台台检查比较慢,所以使用异步,全部测试完返回结果;

@Override
    public List<String> monitorDevice() {
        // for改成异步
        ExecutorService executorService = Executors.newFixedThreadPool(DeviceEnum.values().length);
        List<CompletableFuture<String>> futures = new ArrayList<>();
        for (DeviceEnum deviceEnum : DeviceEnum.values()) {
            String deviceName = deviceEnum.getKey();
            String ipAddress = deviceEnum.getValue();
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                boolean deviceStatus = isDeviceReachable(ipAddress);
                if (!deviceStatus) {
                    return deviceName + "(" + ipAddress + ")" + "设备不在线";
                } else {
                    return null;
                }
            }, executorService);
            futures.add(future);
        }
        List<String> list = new ArrayList<>();
        futures.stream()
                .map(CompletableFuture::join)
                .filter(Objects::nonNull)
                .forEach(list::add);
        executorService.shutdown();
        System.out.println(list); 
        // 输出结果
        return list;
    }

测试在线方法

private static boolean isDeviceReachable(String ipAddress) {
        try {
            InetAddress inet = InetAddress.getByName(ipAddress);
            return inet.isReachable(5000);
        } catch (IOException e) {
            return false;
        }
    }

多台设备可以使用枚举维护

@AllArgsConstructor
@Getter
public enum DeviceEnum {
    A("A","192.168.2.23"),
    B("B","192.168.2.24"),
    C("C","192.168.2.25"),
    D("D","192.168.2.27"),
    E("E","192.168.2.26"),
    F("F","192.168.2.29"),
    G("G","192.168.2.30"),
    H("H","192.168.2.31"),
 
    ;

    private String key;
    private String value;
    private static final Map<String, DeviceEnum> VALUE_MAP = new HashMap<>();

    static {
        for (DeviceEnum anEnum : DeviceEnum.values()) {
            VALUE_MAP.put(anEnum.value, anEnum);
        }
    }

    public static DeviceEnum getByValue(String value) {
        return VALUE_MAP.get(value);
    }

}

java检测电脑是否在线_IP

举报

相关推荐

0 条评论