Netty integrated into spring-boot

I. Overview:

Netty is integrated into spring-boot. The main implementation is to record the channel after startup with variables, and then inject the beans of the server class into spring, manage its life cycle and monitor its status through spring, and so on.

1. Create the SpringNettyServer class

@Component  // 主要点: 将此类的实例添加到spring中
public class SpringNettyServer {

	private Logger logger = LoggerFactory.getLogger(SpringNettyServer.class);

	private final EventLoopGroup parentGroup = new NioEventLoopGroup(1);

	private final EventLoopGroup childGroup = new NioEventLoopGroup();

	private Channel channel;

	public ChannelFuture bind(InetSocketAddress address) {
		ChannelFuture channelFuture = null;
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 128).childHandler(new MyChannelInitializer());
			channelFuture = b.bind(address).sync();
			channel = channelFuture.channel(); // 主要点:用变量记录启动后的channel
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (null != channelFuture && channelFuture.isSuccess()) {
				logger.info("itstack-demo-netty server start done");
			} else {
				logger.error("itstack-demo-netty server start error");
			}
		}
		return channelFuture;
	}

	/**
	 * 主要点:销毁方法由spring控制
	 * 销毁 
	 */
	public void destroy() {
		if (null == channel)
			return;
		channel.close();
		parentGroup.shutdownGracefully();
		childGroup.shutdownGracefully();
	}

	public Channel getChannel() {
		return channel;
	}

}

2. After the application is started, start nettyServer

@SpringBootApplication
public class Application implements CommandLineRunner{
	
    @Value("${netty.host}")
    private String host;
    
    @Value("${netty.port}")
    private int port;
    
    // 注入nettyServer的bean
    @Autowired
    private SpringNettyServer springNettyServer;

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
	
	@Override
	public void run(String... args) throws Exception {
		InetSocketAddress address = new InetSocketAddress(host, port);
		
		ChannelFuture channelFuture = springNettyServer.bind(address);
		
		Runtime.getRuntime().addShutdownHook(new Thread(() -> springNettyServer.destroy()));
		
		channelFuture.channel().closeFuture().syncUninterruptibly();
	}

}

3. View some status of nettyServer in the controller

@RestController
@RequestMapping(value = "/nettyserver", method = RequestMethod.GET)
public class NettyController {

    @Resource
    private SpringNettyServer springNettyServer;

    @RequestMapping("/localAddress")
    public String localAddress() {
        return "nettyServer localAddress " + springNettyServer.getChannel().localAddress();
    }

    @RequestMapping("/isOpen")
    public String isOpen() {
        return "nettyServer isOpen " + springNettyServer.getChannel().isOpen();
    }

}

 

 

end !!!

Guess you like

Origin blog.csdn.net/shuixiou1/article/details/114903886