SpringBoot+WebSocket实现实时获取系统数据
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 onError(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()); } }