这里主要说使用Netty作为服务端的情况,主要思路:

    • 把Netty需要的资源封装到一个Server类中
    • 基于Spring Bean的生命周期,在Bean创建的时候启动Netty,在Bean销毁的时候关闭Netty

    示例:

    1. package com.semonx.netty;
    2. import java.net.InetSocketAddress;
    3. import javax.annotation.PostConstruct;
    4. import javax.annotation.PreDestroy;
    5. import org.slf4j.Logger;
    6. import org.slf4j.LoggerFactory;
    7. import org.springframework.stereotype.Component;
    8. import io.netty.bootstrap.ServerBootstrap;
    9. import io.netty.channel.ChannelFuture;
    10. import io.netty.channel.ChannelOption;
    11. import io.netty.channel.EventLoopGroup;
    12. import io.netty.channel.nio.NioEventLoopGroup;
    13. import io.netty.channel.socket.nio.NioServerSocketChannel;
    14. @Component
    15. public class NewTankServer {
    16. private final static Logger LOGGER = LoggerFactory.getLogger(NewTankServer.class);
    17. private EventLoopGroup parentGroup = new NioEventLoopGroup();
    18. private EventLoopGroup childGroup = new NioEventLoopGroup();
    19. private int port = 7707;
    20. @PostConstruct
    21. public void start() throws InterruptedException {
    22. ServerBootstrap bootstrap = new ServerBootstrap()
    23. .group(parentGroup, childGroup)
    24. .localAddress(new InetSocketAddress(port))
    25. .channel(NioServerSocketChannel.class)
    26. .childOption(ChannelOption.SO_KEEPALIVE, true)
    27. .childHandler(new ServerInitializer());
    28. ChannelFuture future = bootstrap.bind().sync();
    29. if (future.isSuccess()) {
    30. LOGGER.info("服务启动成功。监听端口: " + port);
    31. }
    32. }
    33. @PreDestroy
    34. public void destroy() {
    35. parentGroup.shutdownGracefully().syncUninterruptibly();
    36. childGroup.shutdownGracefully().syncUninterruptibly();
    37. LOGGER.info("服务成功停止");
    38. }
    39. }