Springboot websocket简单使用
1、在pom.xml导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
2、在Spring Boot项目的service层中创建一个Host类,其中包含一个getCPUUsage()
方法用于定时获取远程CentOS 7系统的CPU使用率。你可以使用JSch库来连接远程服务器,并执行相应的命令来获取CPU使用率。
import org.springframework.scheduling.annotation.Scheduled; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class Host { private Set<WebSocketSession> sessions = new HashSet<>(); public void addSession(WebSocketSession session) { sessions.add(session); } public void removeSession(WebSocketSession session) { sessions.remove(session); } public void sendCPUUsageToAllSessions(double cpuUsage) throws IOException { for (WebSocketSession session : sessions) { session.sendMessage(new TextMessage(String.valueOf(cpuUsage))); } } @Scheduled(fixedRate = 1000) // 每秒执行一次 public void getCPUUsage() throws JSchException, IOException { JSch jSch = new JSch(); Session session = jSch.getSession("username", "hostname", 22); session.setPassword("password"); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand("top -bn 1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'"); channel.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream())); String cpuUsageString = reader.readLine(); double cpuUsage = Double.parseDouble(cpuUsageString); reader.close(); channel.disconnect(); session.disconnect(); sendCPUUsageToAllSessions(cpuUsage); } }
3、在Spring Boot项目中配置WebSocket,创建一个WebSocketHandler用于处理WebSocket连接、消息和关闭操作。
import org.springframework.stereotype.Component; import org.springframework.web.socket.*; import org.springframework.web.socket.handler.TextWebSocketHandler; @Component public class MyWebSocketHandler extends TextWebSocketHandler { private final Host host; public MyWebSocketHandler(Host host) { this.host = host; } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { host.addSession(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // 处理接收到的消息,如果需要的话 } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { host.removeSession(session); } }
4、在Spring Boot的配置类中配置WebSocket相关的Bean和路径映射。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { private final MyWebSocketHandler myWebSocketHandler; @Autowired public WebSocketConfig(MyWebSocketHandler myWebSocketHandler) { this.myWebSocketHandler = myWebSocketHandler; } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler, "/ws").setAllowedOrigins("*"); } }
5、在Spring Boot的启动类上加上@EnableScheduling
6、在你的Vue.js项目中,创建WebSocket连接并处理收到的消息。
socket.onmessage = (event) => { this.tableData = JSON.parse(event.data).data; // 处理接收到的CPU使用率数据 console.log(this.tableData); };
通过以上步骤,你可以实现在Spring Boot的service层通过JSch定时获取远程CentOS 7系统的CPU使用率,并使用WebSocket主动发送给连接的Vue.js项目的页面。在Vue.js项目中,通过创建WebSocket连接并处理接收到的消息,即可实时接收并处理CPU使用率数据。请根据实际情况对代码进行适当修改和优化。记得在Spring Boot的启动类上加上@EnableScheduling
注解启用定时任务。