在实战六中,我们监听多个端口是通过创建多个实例来监听多个端口的,这种方式其实还是有点浪费资源,下面我们再来一种监听多个端口的方法。
直接在之前的代码上简单改动下就可以了,这是利用了Reactor主从模式,可以充分利用bossGroup线程池,如果是多个实例监听多个端口,那么就会有多个bossGroup线程池(workGroup也是多个),这种通常是用在海量客户端接入时使用,如果客户端数量不多,其实也没有必要使用这种方式。
package org.xxx.android.netty.server;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
/**
* Created by zhangkai on 2018/6/11.
* NioEventLoopGroup → EpollEventLoopGroup
NioEventLoop → EpollEventLoop
NioServerSocketChannel → EpollServerSocketChannel
NioSocketChannel → EpollSocketChannel
@Component
*/
public class NettyServer{
private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
ServerBootstrap serverBootstrap = new ServerBootstrap();
EventLoopGroup boss =null;
EventLoopGroup worker =null;
ChannelFuture future = null;
//厂商编码
Integer factoryCode=null;
boolean epoll=true;
int port;
public NettyServer(Integer fc,int port){
this.factoryCode=fc;
this.port=port;
}
@PreDestroy
public void stop(){
if(future!=null){
future.channel().close().addListener(ChannelFutureListener.CLOSE);
future.awaitUninterruptibly();
boss.shutdownGracefully();
worker.shutdownGracefully();
future=null;
logger.info(" 服务关闭 ");
}
}
public void start(){
logger.info