【netty】主动关闭netty server

设计一个可以控制监听端口的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关闭就好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值