首页 > 其他分享 >SpringBoot+WebSocket实现实时获取系统数据

SpringBoot+WebSocket实现实时获取系统数据

时间:2023-03-02 10:00:17浏览次数:43  
标签:1024 WebSocket SpringBoot userId 实时 session operatingSystemMXBean message String

SpringBoot+WebSocket实现实时获取系统数据

  • 引入maven依赖

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>
            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.7.5</version>
            </dependency>
    
            <dependency>
                <groupId>com.github.ulisesbocchio</groupId>
                <artifactId>jasypt-spring-boot</artifactId>
                <version>2.0.0</version>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
                <version>2.1.7.RELEASE</version>
            </dependency>
    
        </dependencies>
    
  • 配置websocket

    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter(){
            return new ServerEndpointExporter();
        }
    }
    
  • 编写websocket类

    @Component
    @Slf4j
    @ServerEndpoint("/websocket/{userId}")
    @EnableScheduling
    public class WebSocket {
        private Session session;
    
        private String userId;
    
        private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
    
        private static ConcurrentHashMap<String,Session> sessionPool = new ConcurrentHashMap<String,Session>();
    
    
        @Scheduled(cron = "0/5 * * * * ?")
        private void configureTasks() throws UnknownHostException {
            InetAddress address = InetAddress.getLocalHost();
            String hostAddress = address.getHostAddress();
            System.out.println(hostAddress);
            String action = "http://"+hostAddress+":8011/websocket/sa";
            HttpRequest.get(action)
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
                    .execute().body();
            System.out.println("定时任务");
        }
    
        @OnOpen
        public void onOpen(Session session,@PathParam(value="userId")String userId) {
            try {
    
                this.session = session;
                this.userId = userId;
                webSockets.add(this);
                sessionPool.put(userId, session);
                log.info("【websocket消息】有新的连接,总数为:"+webSockets.size());
            } catch (Exception e) {
    
            }
        }
    
        @OnClose
        public void onClose() {
            try {
                webSockets.remove(this);
                sessionPool.remove(this.userId);
                log.info("【websocket消息】连接断开,总数为:"+webSockets.size());
            } catch (Exception e) {
            }
        }
        /**
         * 收到客户端消息后调用的方法
         *
         * @param message
         */
        @OnMessage
        public void onMessage(String message) {
            log.info("【websocket消息】收到客户端消息:"+message);
        }
    
        /** 发送错误时的处理
         * @param session
         * @param error
         */
        @OnError
        public void one rror(Session session, Throwable error) {
    
            log.error("用户错误,原因:"+error.getMessage());
            error.printStackTrace();
        }
    
        // 此为广播消息
        public void sendAllMessage(String message) {
            log.info("【websocket消息】广播消息:"+message);
            for(WebSocket webSocket : webSockets) {
                try {
                    if(webSocket.session.isOpen()) {
                        webSocket.session.getAsyncRemote().sendText(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        // 此为单点消息
        public void sendOneMessage(String userId, String message) {
            Session session = sessionPool.get(userId);
            if (session != null&&session.isOpen()) {
                try {
                    log.info("【websocket消息】 单点消息:"+message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        // 此为单点消息(多人)
        public void sendMoreMessage(String[] userIds, String message) {
            for(String userId:userIds) {
                Session session = sessionPool.get(userId);
                if (session != null&&session.isOpen()) {
                    try {
                        log.info("【websocket消息】 单点消息:"+message);
                        session.getAsyncRemote().sendText(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
  • 编写controller

    @RestController
    @RequestMapping("/websocket")
    class haoWebSocketController {
    
        @Resource
        private WebSocket webSocket;
    
    
    
        @GetMapping("/{userId}")
        public void aaaa(@PathVariable("userId") String userId){
            OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
            File[] files = File.listRoots();
            //System.out.println("系统名称:"+operatingSystemMXBean.getName());
            //System.out.println("版本:"+operatingSystemMXBean.getVersion());
            //System.out.println("CPU内核:"+operatingSystemMXBean.getAvailableProcessors());
            //k->G
            //System.out.println("机器总内存:"+Double.valueOf(operatingSystemMXBean.getTotalPhysicalMemorySize())/ 1024 / 1024 / 1024 + "GB");
            //System.out.println("可用内存:"+Double.valueOf(operatingSystemMXBean.getFreePhysicalMemorySize())/ 1024 / 1024 / 1024 + "GB");
            DecimalFormat decimalFormat = new DecimalFormat("0.00%");
            String aa = null;
            if (operatingSystemMXBean.getTotalPhysicalMemorySize() > 0) {
                aa = decimalFormat.format(Double.valueOf(operatingSystemMXBean.getFreePhysicalMemorySize()) / operatingSystemMXBean.getTotalPhysicalMemorySize());
                //System.out.println("可用内存占比:"+decimalFormat.format(Double.valueOf(operatingSystemMXBean.getFreePhysicalMemorySize()) / operatingSystemMXBean.getTotalPhysicalMemorySize()));
            }
    
            JSONObject obj = new JSONObject();
            obj.put("系统名称", operatingSystemMXBean.getName());//业务类型
            obj.put("版本", operatingSystemMXBean.getVersion());//业务类型
            obj.put("CPU内核", operatingSystemMXBean.getAvailableProcessors());//业务类型
            obj.put("机器总内存", Double.valueOf(operatingSystemMXBean.getTotalPhysicalMemorySize())/ 1024 / 1024 / 1024 + "GB");//业务类型
            obj.put("可用内存", Double.valueOf(operatingSystemMXBean.getFreePhysicalMemorySize())/ 1024 / 1024 / 1024 + "GB");//业务类型
            obj.put("内存占用", aa);//业务类型
            //单个用户发送 (userId为用户id)
            webSocket.sendOneMessage(userId, obj.toJSONString());
        }
    }
    

运行测试

image-20230302095211804

标签:1024,WebSocket,SpringBoot,userId,实时,session,operatingSystemMXBean,message,String
From: https://www.cnblogs.com/striver20/p/17170799.html

相关文章

  • SpringBoot——常用配置
    application.yml配置信息spring:profiles:active:devapplication:name:jwt-token-security#Jackson配置项jackson:serialization:......
  • SpringBoot自定义启动时的ASCII艺术字
    1.SpringBoot默认的艺术字2.进入ASCII艺术字网站https://www.bootschool.net/ascii3.把下载的banner.txt文件放在resource目录4.重新启动项目【注意:如果不生效的......
  • SpringBoot
    简介SprintBoot是一款快速开发框架,能够帮助我们快速整合第三方框架不同于SSM项目繁琐的xml配置,SpintBoot去除了xml配置全部采用注解化的方式配置内嵌Tomcat,运行就会启......
  • SpringBoot过滤器获取请求Body
    packagecom.example.springboot.core;importlombok.extern.slf4j.Slf4j;importorg.springframework.stereotype.Component;importjavax.servlet.http.HttpServle......
  • Linux如何查看实时滚动日志
    Linux有多种方法可以查看实时滚动日志。最常用的方法是使用tail命令,它可以显示一个文件的最后几行,并且可以跟踪文件的变化。例如,你可以输入tail-f/var/log/syslog来查看......
  • SpringBoot自定义拦截器和跨域配置冲突的问题
    跨域配置完成以后,又进行拦截器的配置,发现跨域配置失效,以下是原配置@ConfigurationpublicclassCORSConfigimplementsWebMvcConfigurer{@BeanpublicWebMv......
  • SpringBoot Actuator RCE 漏洞总结
    一、SpringBootenv获取*敏感信息 当我们直接访问springboot站点时,可以看到某些password字段填充了*通过${name}可以获取明文字段  2.配置不当导致敏感信息......
  • springboot 自动装配之@ConditionalOnClass,@ConditionalOnMissingClass
    @ConditionalOnClass表示如果有后面的类,那么就加载这个自动配置@ConditionalOnMissingClass如果没有后面的类,才自动配置这2个注解对实现自动配置很重要。@Configuration......
  • SpringBoot整合Spring Security
    1快速入门在项目中直接引入SpringSecurity的依赖<!--springSecurity--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-bo......
  • websocketpp中心跳函数使用记录
    依赖的开源库:WebSocket++|ZaphoydStudiosserver发送pingclient响应pong问题:通过set_ping_handler注册on_ping函数后,发送一次心跳,却收到两次pong;分析:抓包分析客户......