Spring Boot Netty WebSocket Quick Start

Foreword

Whenever SpringBoot is used for Weboscket development, the easiest thing to think of is spring-boot-starter-websocket(or spring-websocket). It allows us to use annotations, very simple Websocket development, let us pay more attention to business logic. It uses Tomcat at the bottom, and it is not too heavy to put the entire Tomcat in a WebSocket service, but in the scenario of large data volume and high concurrency, its performance is not very ideal.

Netty, a high-performance NIO network programming framework, still performed well when the number of pushes soared. (There are many discussions on performance and performance on the Internet, but here is not enough to explain.) Many popular open source projects are using Netty, such as: Dubbo, Storm, Spark, Elasticsearch, Apache Cassandra, etc., thanks to Netty's high concurrency and transmission Fast and well packaged.

However, it is not a comfortable thing to integrate Netty in the Spring Boot project to develop WebSocket, which will make you pay too much attention to the implementation of non-business logic. So, is there a framework that makes it easy, even elegant, to use Netty to develop WebSockets in SpringBoot projects, and it can be spring-boot-starter-websocketseamlessly migrated from projects that use development?

netty-websocket-spring-boot-starter

This is an open source framework. Through it, we can spring-boot-starter-websocketuse annotations to develop as we just need to focus on the required events (such as OnMessage). And the bottom layer is Netty. When you need to adjust the parameters, you only need to modify the configuration parameters, without too much care about the settings of the handler.

Quick start

  • Create a Spring Boot project (v2.0.0 or higher) and add dependencies:
<dependency>
	<groupId>org.yeauty</groupId>
	<artifactId>netty-websocket-spring-boot-starter</artifactId>
	<version>0.6.3</version>
</dependency>
  • New an ServerEndpointExporterobject, handed to the Spring container, said to open the WebSocket function: 
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
  • Plus on the endpoint class @ServerEndpoint, @Componentnotes, and add in the appropriate way @OnOpen, @OnClose, @OnError, @OnMessagenotes (do not want to focus on a specific event may not be added corresponding notes): 
@ServerEndpoint
@Component
public class MyWebSocket {

    @OnOpen
    public void onOpen(Session session, HttpHeaders headers) throws IOException {
        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!");
    }
}
  • A high-performance WebSocket server is completed, just run it.

test

  • The server is finished. Next, you need to test it to see the effect
  • First, create a new html file and push the page out
<!DOCTYPE html>
<html lang="en">
<body>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="send" οnclick="send()">
</body>
<script>
    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) {
        alert("连接关闭");
    };

    function send() {
        var text = document.getElementById("text").value
        websocket.send(text);
    }
</script>
</html>
  • After the page is finished, directly open the above html file with Chrome to connect to your WebSocket service.

to sum up

This framework is based on Netty, so just use Netty's optimization concept. Such as: 0 copies of off-heap memory, adjustment of receive and send buffers, adjustment of high and low write water levels, etc.

After fully tuning the production environment, Netty can even be 20 times more efficient than Tomcat. (Of course, this is a specific scenario)

Framework detailed documentation: https://github.com/YeautyYE/netty-websocket-spring-boot-starter

Published 203 original articles · won praise 6 · views 4476

Guess you like

Origin blog.csdn.net/weixin_42073629/article/details/105609293