设计一个可以控制监听端口的http服务端的开启和关闭的功能,启动部分比较简单,关闭查了一下,找到了功能,以下是demo
import com.wangjx.swallow.common.server.IServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
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;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
@Slf4j
public class HttpServer implements IServer {
EventLoopGroup boss = null;
EventLoopGroup work = null;
ServerBootstrap bootstrap = null;
Channel channel = null;
public ChannelHandler channelHandler;
int port ;
public HttpServer(int port, ChannelHandler channelHandler){
this.port = port;
this.channelHandler = channelHandler;
}
@Override
public int getPort() {
return this.port;
}
public void start() {
try {
bootstrap = new ServerBootstrap();
boss = new NioEventLoopGroup();
work = new NioEventLoopGroup();
bootstrap.group(boss, work)
.handler(new LoggingHandler(LogLevel.DEBUG))
.channel(NioServerSocketChannel.class)
.childHandler(new HttpServerInitializer(channelHandler));
ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync();
System.out.println("http server start up on port: " + port);
channel = f.channel();
f.channel().closeFuture().sync();
} catch (Exception e) {
log.error("start netty http server exception", e);
} finally {
work.shutdownGracefully();
boss.shutdownGracefully();
}
}
public void stop() {
try {
if (channel != null) {
log.info("http server is stopping listen port {} ...", port);
channel.close();
channel = null;
log.info("http server is stopped to listen port {} !", port);
}
} catch (Exception e) {
log.error("close netty http server exception", e);
}
}
@Override
public void run() {
start();
}
}
start()方法就是启动server的方法,stop()方法就是停止server的方法,stop()方法中可以看到,就是将启动过程中获取到的channel关闭就好。