本文共 3041 字,大约阅读时间需要 10 分钟。
在《》中,实现了一个最简单的Netty 整合webSocket 的Demo。
引入springboot依赖,父工程com.ct.netty的pom文件中增加:
org.springframework.boot spring-boot-starter-parent 2.5.0
引入springboot依赖,子模块工程com.ct.netty.http的pom中增加:
org.springframework.boot spring-boot-starter-web
server: port: 8089
package com.ct.netty.http;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * @Author LaoHa * @Date 2021/6/8 */@SpringBootApplicationpublic class AppServer { public static void main(String[] args) { SpringApplication.run(AppServer.class, args); }}
注意:@Component
package com.ct.netty.http.IIIspringboot;import com.ct.netty.http.IIwebsocket.WsServerInitializer;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.stereotype.Component;/** * 服务端基本配置,通过一个静态单例类,保证启动时候只被加载一次 * * @Author LaoHa * @Date 2021/6/8 */@Componentpublic class WsServer { /** * 单例静态内部类 * */ public static class SingletonWsServer { static final WsServer instance = new WsServer(); } public static WsServer getInstance() { return SingletonWsServer.instance; } private final ServerBootstrap server; public WsServer() { EventLoopGroup mainGroup = new NioEventLoopGroup(); EventLoopGroup subGroup = new NioEventLoopGroup(); server = new ServerBootstrap(); server.group(mainGroup, subGroup) .channel(NioServerSocketChannel.class) //添加自定义初始化处理器 .childHandler(new WsServerInitializer()); } public void start() { ChannelFuture future = this.server.bind(8087); System.err.println("netty 服务端启动成功 ....."); }}
同《》
同《》
package com.ct.netty.http.IIIspringboot;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.stereotype.Component;/** * netty服务端启动加载配置 * 实现了ApplicationListener这个接口,这样springboot容器启动完毕就可以加载netty的相关配置信息 * * @Author LaoHa * @Date 2021/6/8 */@Componentpublic class StartNettyServerConfig implements ApplicationListener{ @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext().getParent() == null) { WsServer.getInstance().start(); } }}
运行AppServer,启动服务端。其他
同《》idea提交git
转载地址:http://olmdi.baihongyu.com/