构建高性能的WebSocket
构建背景
SpringBoot作为最近比较主流的开发框架,可以使开发者快速、优雅的创建应用。结合最近公司小伙伴对WebSocket提及的次数暴增,因此介绍一下如何使用SpringBoot + Netty快速构建的WebSocket项目。
创建SpringBoot项目
可以在SpringBoot快速的初始化一个SpringBoot项目,启动器仅选择Web即可;
添加依赖
添加Netty-WebSocket的依赖项并等待IDE加载完成对应的包;
<dependency>
<groupId>org.yeauty</groupId>
<artifactId>netty-websocket-spring-boot-starter</artifactId>
<version>0.6.2</version>
</dependency>
配置服务发布Bean
需要添加对服务发布用到的类进行配置,配置如下:
@Configuration
public class WebSocketConfiguration
{
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
ServerEndpointExporter exporter = new ServerEndpointExporter();
return exporter;
}
}
创建WebSocket消息监听处理类
最后,我们需要创建一个用于接收请求和处理请求的类,该类的作用相当于一个Controller:
@ServerEndpoint
@Component
public class WebSocketServer
{
@OnOpen
public void onOpen(Session session, HttpHeaders headers)
{
//TODO
System.out.println("Connected..");
}
@OnClose
public void onClose(Session session)
{
//TODO
System.out.println("DisConnected..");
}
@OnError
public void onError(Session session, Throwable exception)
{
//TODO
exception.printStackTrace();
}
@OnMessage
public void OnMessage(Session session, String message)
{
//TODO
System.out.println("Message Receive & Send Method..");
}
}
创建消息页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>WebSocket测试</title>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="send" onclick="send()">
</body>
<script type="text/javascript">
var msg = document.getElementById("msg");
var wsServer = 'ws://127.0.0.1:80';
var websocket = new WebSocket(wsServer);
//监听连接打开
websocket.onopen = function (evt) {
msg.innerHTML = "The connection is open";
};
//监听服务器数据推送
websocket.onmessage = function (evt) {
msg.innerHTML += "<br>" + evt.data;
};
//监听连接关闭
websocket.onclose = function (evt) {
console.info("连接已关闭...");
};
function send() {
var text = document.getElementById("text").value;
websocket.send(text);
}
</script>
</html>
测试
最后,运行SringBoot项目(既打开WebSocket服务),打开对应的HTML页面,完成请求的测试即可。