springboot启动成功后启动netty服务端

springboot提供了ApplicationRunner接口,在服务器启动成功后,可以添加自己的业务逻辑

 1 @Component
 2 public class NettyStartListener implements ApplicationRunner  {
 3     
 4     @Autowired
 5     private SocketServer socketServer;
 6 
 7     
 8 
 9 
10     @Override
11     public void run(ApplicationArguments args) throws Exception {
12         
13         socketServer.start();
14     }
15 
16 }

2.创建服务端

 1 @Slf4j
 2 @Component
 3 public class SocketServer {
 4     @Autowired
 5     private SocketInitializer socketInitializer;
 6 
 7     @Setter
 8     private ServerBootstrap serverBootstrap;
 9 
10     /**
11      * netty服务监听端口
12      */
13     @Value("${listen.server.port:10988}")
14     private int port;
15     /**
16      * 主线程组数量
17      */
18     @Value("${netty.bossThread:1}")
19     private int bossThread;
20 
21     /**
22      * 启动netty服务器
23      */
24     public void start() {
25         this.init();
26         try {
27             Channel channel = this.serverBootstrap.bind(this.port).sync().channel();
28             log.info("Netty started on port: {} (TCP) with boss thread {}", this.port, this.bossThread);
29             channel.closeFuture().sync();
30         } catch (InterruptedException e) {
31             // TODO Auto-generated catch block
32             e.printStackTrace();
33         }
34     }
35 
36     /**
37      * 初始化netty配置
38      */
39     private void init() {
40         // 创建两个线程组,bossGroup为接收请求的线程组,一般1-2个就行
41         NioEventLoopGroup bossGroup = new NioEventLoopGroup(this.bossThread);
42         // 实际工作的线程组
43         NioEventLoopGroup workerGroup = new NioEventLoopGroup();
44         this.serverBootstrap = new ServerBootstrap();
45         this.serverBootstrap.group(bossGroup, workerGroup) // 两个线程组加入进来
46                 .channel(NioServerSocketChannel.class)  // 配置为nio类型
47                 .childHandler(this.socketInitializer); // 加入自己的初始化器
48     }
49 }

创建ChannelInitializer

 1 @Component
 2 public class SocketInitializer extends ChannelInitializer<SocketChannel> {
 3     //这里可以使用Autowired引入需要的bean,通过参数的形式传给handler12     
13     @Override
14     protected void initChannel(SocketChannel ch) throws Exception {
15         ChannelPipeline pipeline = ch.pipeline();
16         pipeline.addLast(new StringDecoder());
17         pipeline.addLast(new StringEncoder());
18         pipeline.addLast(new IdleStateHandler(6, 0, 0,TimeUnit.SECONDS));
19         pipeline.addLast(new ServerHandler());
20     }
21 }

创建handler 

public class ServerHandler extends SimpleChannelInboundHandler<String> {
 

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String data) throws Exception {
        //TODO自己的业务逻辑

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        updateState(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        updateState(ctx);
    }

    /**
     * @param ctx
     * @throws SQLException
     */
    private void updateState(ChannelHandlerContext ctx) {
        //TODO业务逻辑
    }
}

本文所用的netty版本为

    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-all</artifactId>
      <version>4.1.35.Final</version>
    </dependency>

 

posted @ 2022-05-07 09:54  转身瞬间  阅读(1077)  评论(0)    收藏  举报