springboot+vue+element 整合websocket+定时任务+sigar实现对系统的实时监控

本文介绍了如何整合springboot、vue和element来实现系统的实时监控,包括配置pom.xml、引入sigar、设置websocket连接和定时任务。通过sigar获取系统信息,利用websocket传输数据,前端使用vue和element展示实时数据,每3秒更新一次。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

启动springboot

第一步配置pom.xml

网上教程很多,直接截图看配置吧,高效点,pom.xml里面需要加入websocket依赖,必须的。
在这里插入图片描述

第2步 加入sigar

在resources文件先创建一个sigar.so文件,然后把相应的文件加进去,文件的下载可以百度搜一下就行。
在这里插入图片描述
也可以直接用maven引入:
在这里插入图片描述

springboot启动类

因为这只是一个demo不需要配置很多功能,就配个最简单的就好了
在这里插入图片描述
@springBootApplication 是启动用的
@EnableScheduling是定时任务用的

配置跨域

因为我们前端用的vue嘛 自然端口不一致需要进行跨域,配置如下:
在这里插入图片描述

@Configuration
public class MywWebMvcConfig implements WebMvcConfigurer {

    // 全局跨域请求
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("*")
                .maxAge(1800);
    }
}

配置fastJson

下面是配置fastjson的
在这里插入图片描述

@Configuration
public class MyFastJsonConfig {

    @Bean
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {

        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd");
        config.setCharset(Charset.forName("UTF-8"));
        config.setSerializerFeatures(
//                SerializerFeature.WriteClassName,  // 输出类名
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty
        );
        converter.setFastJsonConfig(config);
        return converter;
    }
}

配置socket连接

创建一个JqWebSocket 类

@Component
@ServerEndpoint(value = "/websocket")
public class JqWebSocket {

    private Session session = null;

    private Integer linkCount=0;

    private static CopyOnWriteArraySet<JqWebSocket> webSocketSet = new CopyOnWriteArraySet<JqWebSocket>();

    /**
     * 新的客户端连接调用的方法
     * @param session
     * @throws IOException
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
//        System.out.println("-------------有新的客户端连接----------");
        linkCount++;
        this.session = session;
        webSocketSet.add(this);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        try {
            sendMessage("change");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendMessage(String message) throws IOException{
        for (JqWebSocket item : webSocketSet) {
            item.session.getBasicRemote().sendText(message);
        }
    }

    @OnClose
    public void onClose(){
        linkCount--;
        webSocketSet.remove(this);
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }
}

再建一个WebSocketConfig 类

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

创建一个ISigarConfigService接口类

public interface ISigarConfigService {

    public SystemDTO qureySystemInfo() throws Exception;
}

创建一个SigarConfigServiceImpl接口实现类

@Service
public class SigarConfigServiceImpl implements ISigarConfigService{
    static {
        try {
            initSigar();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public static void initSigar() throws IOException {
        SigarLoader loader = new SigarLoader(Sigar.class);
        String lib = null;
        try {
            lib = loader.getLibName();
            System.out.println("so文件"+lib);
        } catch (Exception e) {
            e.printStackTrace();
        }

        ResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("classpath:/sigar.so/" + lib);
        if (resource.exists()){
            InputStream is = resource.getInputStream();
            File tempDir = new File("D:\\var\\log");
            if (!tempDir.exists()){
                tempDir.mkdirs();
            }
            BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(tempDir, lib), false));
            int lentgh = 0;
            while ((lentgh = is.read()) != -1){
                os.write(lentgh);
            }
            is.close();
            os.close();

        }
    }

    /**
     * 以太网信息
     * @throws SigarException
     */
    private void ethernet(SystemDTO systemDTO) throws SigarException{
        Sigar sigar = new Sigar();
        String[] ifaces = sigar.getNetInterfaceList();
        List<EthernetPO> ethernetPOList = new ArrayList<>();
        for (int i = 0; i < ifaces.length; i++){
            NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
            if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())
                    || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
                    || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())){
                continue;
            }
            EthernetPO ethernetPO = new EthernetPO();
            ethernetPO.setIpAddress(cfg.getAddress()); // IP地址
            ethernetPO.setBroadcast(cfg.getBroadcast()); // 网关广播地址
            ethernetPO.setHwaddr(cfg.getHwaddr()); // 网卡MAC地址
            ethernetPO.setNetmask(cfg.getNetmask()); // 子网掩码
            ethernetPO.setDescription(cfg.getDescription()); // 网卡描述信息
            ethernetPO.setType(cfg.getType()); // 网卡类型
            ethernetPOList.add(ethernetPO);
        }
        systemDTO.setEthernetPOS(ethernetPOList);
    }

    /**
     * 网络信息
     * @throws Exception
     */
    private void net(SystemDTO systemDTO) throws Exception{
        Sigar sigar = new Sigar();
        String ifNames[] = sigar.getNetInterfaceList();
        List<NetWorkPO> netWorkPOS = new ArrayList<>();
        for (int i = 0; i < ifNames.length; i++){
            String name = ifNames[i];
            NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
            NetWorkPO netWorkPO = new NetWorkPO();
            netWorkPO.setNetName(name); // 网络设备名
            netWorkPO.setIpAddress(ifconfig.getAddress()); // IP地址
            netWorkPO.setNetmask(ifconfig.getNetmask()); // 子网掩码
            if ((ifconfig.getFlags() & 1L) <= 0L){
                continue;
            }
            NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
            netWorkPO.setRxPackets(ifstat.getRxPackets()); // 接收的总包裹数
            netWorkPO.setTxPackets(ifstat.getTxPackets()); // 发送的总包裹数
            netWorkPO.setRxBytes(ifstat.getRxBytes()); // 接收到的总字节数
            netWorkPO.setRxErrors(ifstat.getRxErrors()); // 接收到的错误包数
            netWorkPO.setTxErrors(ifstat.getTxErrors()); // 发送数据包时的错误数
            netWorkPO.setRxDropped(ifstat.getRxDropped()); // 接收时丢弃的包数
            netWorkPO.setTxDropped(ifstat.getTxDropped()); // 发送时丢弃的包数
            netWorkPOS.add(netWorkPO);
        }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值