springBoot + netty搭建高性能 websocket 服务 & 性能测试(包含python 测试脚本)
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class NettyServer implements ApplicationListener<ContextRefreshedEvent> {
private static final int PORT = 8080;
@Autowired
private WebSocketServerInitializer webSocketServerInitializer;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
start();
}
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(webSocketServerInitializer);
ChannelFuture f = b.bind(PORT).sync();
System.out.println("Web socket server started at port " + PORT);
f.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
这段代码实现了Netty服务器的启动,并在Spring容器完全刷新之后绑定到指定端口。它使用了NioEventLoopGroup
和NioServerSocketChannel
来实现非阻塞I/O。在实际部署时,你可能需要根据实际需求对代码进行相应的调整,例如启动参数配置、安全性配置等。
评论已关闭