0
点赞
收藏
分享

微信扫一扫

websocket系列:基于netty-websocket-spring-boot-starter轻松实现高性能websocket

王小沫 2022-12-07 阅读 130


前言

本着死磕websocket的精神继续鼓捣websocket的实现方式。本文通过介绍如何基于​​netty-websocket-spring-boot-starter​​轻松实现高性能websocket。

一、介绍

netty-websocket-spring-boot-starter是一个开源的框架。通过它,我们可以像spring-boot-starter-websocket一样使用注解进行开发,只需关注需要的事件(如OnMessage)。并且底层是使用Netty,netty-websocket-spring-boot-starter其他配置和spring-boot-starter-websocket完全一样,当需要调参的时候只需要修改配置参数即可,无需过多的关心handler的设置。

git地址:​​https://github.com/YeautyYE/netty-websocket-spring-boot-starter/blob/master/README_zh.md​​

Netty为什么传输快?
Netty的传输快其实也是依赖了NIO的一个特性——零拷贝。我们知道,Java的内存有堆内存、栈内存和字符串常量池等等,其中堆内存是占用内存空间最大的一块,也是Java对象存放的地方,一般我们的数据如果需要从IO读取到堆内存,中间需要经过Socket缓冲区,也就是说一个数据会被拷贝两次才能到达他的的终点,如果数据量大,就会造成不必要的资源浪费。

Netty针对这种情况,使用了NIO中的另一大特性——零拷贝,当他需要接收数据的时候,他会在堆内存之外开辟一块内存,数据就直接从IO读到了那块内存中去,在netty里面通过ByteBuf可以直接对这些数据进行直接操作,从而加快了传输速度。

Netty和Tomcat有什么区别?
Netty和Tomcat最大的区别就在于通信协议,Tomcat是基于Http协议的,他的实质是一个基于http协议的web容器,但是Netty不一样,他能通过编程自定义各种协议,因为netty能够通过codec自己来编码/解码字节流,完成类似redis访问的功能,这就是netty和tomcat最大的不同。

二、项目实战

1.添加依赖

<dependency>
<groupId>org.yeauty</groupId>
<artifactId>netty-websocket-spring-boot-starter</artifactId>
<version>0.10.0</version>
</dependency>

2.核心类MyWebSocket

在端点类上加上@ServerEndpoint注解,并在相应的方法上加上@BeforeHandshake、@OnOpen、@OnClose、@OnError、@OnMessage、@OnBinary、@OnEvent注解,样例如下:

@ServerEndpoint(path = "/myWs",host = "${ws.host}",port = "${ws.port}")
//@Component
public class MyWebSocket {

/**
*建立ws连接前的配置
*/
/* @BeforeHandshake
public void handshake(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
//采用stomp子协议
session.setSubprotocols("stomp");
if (!"ok".equals(req)){
System.out.println("Authentication failed!");
session.close();
}
}*/

@OnOpen
public void onOpen(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
System.out.println("new connection");
}

@OnClose
public void onClose(Session session) throws IOException {
System.out.println("one connection closed");
}

@OnError
public void onError(Session session, Throwable throwable) {
throwable.printStackTrace();
}

@OnMessage
public void onMessage(Session session, String message) {
System.out.println("接收的消息为:" + message);
session.sendText("Hello Netty!");
}

@OnBinary
public void onBinary(Session session, byte[] bytes) {
for (byte b : bytes) {
System.out.println(b);
}
session.sendBinary(bytes);
}

@OnEvent
public void onEvent(Session session, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
switch (idleStateEvent.state()) {
case READER_IDLE:
System.out.println("read idle");
break;
case WRITER_IDLE:
System.out.println("write idle");
break;
case ALL_IDLE:
System.out.println("all idle");
break;
default:
break;
}
}
}
}

注解说明:
​​​注意以下注解都是在org.yeauty.*的包下,不要错误引入成javax.websocket包的注解​​​。
@Component也不必添加,MyWebSocket不是单例类,每个session连接共享一个MyWebSocket实例对象。关于session的管理可以参考之前代码中的WsSessionManager类。

@ServerEndpoint

当ServerEndpointExporter类通过Spring配置进行声明并被使用,它将会去扫描带有@ServerEndpoint注解的类 被注解的类将被注册成为一个WebSocket端点 所有的配置项都在这个注解的属性中 ( 如:@ServerEndpoint("/ws") )

更多属性配置:

websocket系列:基于netty-websocket-spring-boot-starter轻松实现高性能websocket_websocket


完整属性配置项,可以查看官网。

@BeforeHandshake
当有新的连接进入时,对该方法进行回调 注入参数的类型:Session、HttpHeaders…

@OnOpen
当有新的WebSocket连接完成时,对该方法进行回调 注入参数的类型:Session、HttpHeaders…

@OnClose
当有WebSocket连接关闭时,对该方法进行回调 注入参数的类型:Session

@OnError
当有WebSocket抛出异常时,对该方法进行回调 注入参数的类型:Session、Throwable

@OnMessage
当接收到字符串消息时,对该方法进行回调 注入参数的类型:Session、String

@OnBinary
当接收到二进制消息时,对该方法进行回调 注入参数的类型:Session、byte[]

@OnEvent
当接收到Netty的事件时,对该方法进行回调 注入参数的类型:Session、Object

3.启动类SpringNettyWebsocketApplication

@SpringBootApplication
//@EnableWebSocket
public class SpringNettyWebsocketApplication {

public static void main(String[] args) {
SpringApplication.run(SpringNettyWebsocketApplication.class, args);
}
}

说明:
注意这里的@EnableWebSocket不是必须的,可以不用添加。

4.属性文件application.properties

server.port=8080

#ws相关属性配置
ws.host=0.0.0.0
ws.port=8333
# 解决返回页面中文乱码问题
server.servlet.encoding.force=true
server.servlet.encoding.charset=UTF-8

5.测试页面index.html

<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>

<body>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message"></div>


</body>

<script type="text/javascript">

let ws = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
ws = new WebSocket("ws://localhost:8333/myWs");
}
else {
alert('当前浏览器 Not support websocket')
}

//连接发生错误的回调方法
ws.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
};

//连接成功建立的回调方法
ws.onopen = function(event) {
console.log("ws调用连接成功回调方法")
//ws.send("")
}
//接收到消息的回调方法
ws.onmessage = function(message) {
console.log("接收消息:" + message.data);
if (typeof(message.data) == 'string') {
setMessageInnerHTML(message.data);
}
}
//ws连接断开的回调方法
ws.onclose = function(e) {
console.log("ws连接断开")
//console.log(e)
setMessageInnerHTML("ws close");
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
console.log(innerHTML)
document.getElementById('message').innerHTML += '接收的消息:' + innerHTML + '<br/>';
}

//关闭连接
function closeWebSocket() {
ws.close();
}


//发送消息
function send(msg) {
if(!msg){
msg = document.getElementById('text').value;
document.getElementById('message').innerHTML += "发送的消息:" + msg + '<br/>';
ws.send(msg);
}
}
</script>
</html>

三、效果演示

websocket系列:基于netty-websocket-spring-boot-starter轻松实现高性能websocket_spring_02

总结

通过引入netty-websocket-spring-boot-starter的依赖,轻松实现了基于netty的高性能websocket,忽略了netty的底层实现逻辑。
相关核心注解和jdk里面默认的注解基本保持一致。使用的时候需注意引入的注解和类的路径是否正确。
@ServerEndpoint注解中添加了许多属性控制,可以根据需要进行相关配置。

参考:​​netty-websocket-spring-boot-starter的git地址​​ 参考:Springboot2构建基于Netty的高性能Websocket服务器(netty-websocket-spring-boot-starter)


举报

相关推荐

Netty Websocket

0 条评论