netty整合到spring-boot中

一、概述:

netty整合到spring-boot中,主要实现方式,是通过用变量记录启动后的channel,然后server的类的bean注入到spring中,通过spring管理其生命周期以及监控其状态等等。

1、创建SpringNettyServer类

@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、application启动完成,进行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、controller中查看nettyServer一些状态

@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 !!!

猜你喜欢

转载自blog.csdn.net/shuixiou1/article/details/114903886