springboot集成Netty

一、Netty介绍

Netty的系列文章,正在更新中

二、Netty集成

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
</dependency>

2.1、配置文件

# netty配置
netty:
  boss: 1 #boss线程数量 默认为cpu线程数*2
  worker: 4 #worker线程数量 默认为cpu线程数*2
  timeout: 6000 #连接超时时间 默认为30s
  port: 7000 #服务器主端口 默认7000
  portSalve: 7001 #服务器备用端口 默认70001
  host: 127.0.0.1  #服务器地址 默认为本地
  tcp: 1024  #tcp参数 1024个队列

2.2、配置类

import com.mofeng.blog.controller.IMController.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties
public class NettyConfig {
    @Value("${netty.boss}")
    private Integer boss;
    @Value("${netty.worker}")
    private Integer worker;
    @Value("${netty.timeout}")
    private Integer timeout;

    @Value("${netty.tcp}")
    private Integer tcp;

    @Autowired
    private ServerHandler serverHandler;//标记1 注意点

    /**
     * boss 线程池
     * 负责客户端连接
     *
     * @return
     */
    @Bean
    public NioEventLoopGroup boosGroup() {
        return new NioEventLoopGroup(boss);
    }

    /**
     * worker 线程池
     * 负责业务处理
     *
     * @return
     */
    @Bean
    public NioEventLoopGroup workerGroup() {
        return new NioEventLoopGroup(worker);
    }

    /**
     * 服务器启动器
     *
     * @return
     */
    @Bean
    public ServerBootstrap serverBootstrap() {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .group(boosGroup(), workerGroup())   //设置主从线程组
                .channel(NioServerSocketChannel.class) //设置nio双向通道
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout) // 指定连接超时时间
                .option(ChannelOption.SO_BACKLOG, tcp) // tcp参数 1024个队列
                .childHandler(serverHandler); // 字处理器,用于处理workerGroup中的任务
        return serverBootstrap;
    }
}

2.3、处理器

ServerHandler

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.channel.socket.SocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ServerHandler extends ChannelInitializer<SocketChannel> {

    @Autowired
    private WebSocketHandler webSocketHandler;//标记2 注意点
    /**
     * 初始化通道以及配置对应管道的处理器
     *
     * @param ch
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        pipeline
                //添加http编码解码器
                .addLast(new HttpServerCodec())
                //支持大数据流
                .addLast(new ChunkedWriteHandler())
                //对http消息做聚合操作,FuLLHttpRequest、 FuLLHttpResponse
                .addLast(new HttpObjectAggregator(1024 * 64))
                //websocket访问路径
                .addLast(new WebSocketServerProtocolHandler("/"))
                .addLast(webSocketHandler);//指定处理器
    }
}

WebSocketHandler

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@ChannelHandler.Sharable
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    /**
     * 前端连接
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("前端连接进来了");
        ctx.fireChannelActive();
    }

    /**
     * 连接掉线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("前端连接断开了");
        ctx.fireChannelInactive();
    }


    /**
     * 读取客户端信息
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("发消息来了,消息是{}", msg.text());
    }

    /**
     * 发生异常时
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
     log.info("出现异常了");
    }
}

三、注意点

以上代码中标记的注意点,这里的所有Handler都加了@Component注解,所以,都交给了springboot管理,千万不要new 新的对象,不然在这些Handler里面就不能调用mapper里的方法了。

以上是近期自学和各种百度的,只是简单的配置一下,如有错误,请劳烦指正。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值