一、 背景介绍
最近研究 Jenkins,发现它的日志能动态输出到网页,十分不错,
本文就基于 SpringBoot 简单实现下如何把后台消息源源不断地打印到网页上
二、 实现步骤
2.1 在你的 SpringBoot 项目中引入 websocket 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
2.2 编写 Configuration,配置 websocket 的 endpoint
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
}
}
2.3 编写一个测试 Controller(实际非必需,这里是为了向网页客户端发送数据)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class WebSocketController {
@Autowired
SimpMessagingTemplate messagingTemplate;
@GetMapping("/websocket/print/{msg}")
public String print(@PathVariable String msg) {
messagingTemplate.convertAndSend("/topic/print",msg);
return msg;
}
}
2.4 编写客户端网页程序
// 这里连接 endpoint 地址,即 /websocket
var socket = new SockJS('http://localhost:9000/websocket');
// 这里要与messagingTemplate.convertAndSend()地址一致,即 /topic/print
stompClient.subscribe('/topic/print', function(event) {...});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket Logger</title>
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.js"></script>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
<button οnclick="openSocket()">开启日志</button><button οnclick="closeSocket()">关闭日志</button>
<div id="log-container" style="height: 450px; overflow-y: scroll; background: #333; color: #aaa; padding: 10px;">
<div></div>
</div>
</body>
<script>
var stompClient = null;
$(document).ready(function() {openSocket();});
function openSocket() {
if(stompClient==null){
var socket = new SockJS('http://localhost:9000/websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
stompClient.subscribe('/topic/print', function(event) {
$("#log-container div").append(event.body).append("<br/>");
$("#log-container").scrollTop($("#log-container div").height() - $("#log-container").height());
},{});
});
}
}
function closeSocket() {
if (stompClient != null) {
stompClient.disconnect();
stompClient=null;
}
}
</script>
</body>
</html>
2.5 实验截图