NettyがSpring-Bootに統合されました

I.概要:

Nettyはspring-bootに統合されています。主な実装は、起動後にチャネルを変数で記録し、サーバークラスの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.アプリケーションの起動後、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.コントローラーで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();
    }

}

 

 

終わり !!!

おすすめ

転載: blog.csdn.net/shuixiou1/article/details/114903886