Netty之ServerBootstrap源码分析

本文是对Netty的服务端ServerBootstrap类的简单分析,以此来学习Netty源码的设计思想,通过本文你将了解Netty是如何创建启动类的,如有错误请指出,谢谢。

ServerBootstrap启动

1.构造启动类

# 创建启动类
ServerBootstrap bootstrap = new ServerBootstrap();

2.注册基本信息

# 1.group:将创建的bossGroup与workerGroup线程组添加到启动类中
# 2.channel:设置创建消息事件传输的管道channel,这里还可以设置其它类型的channel用来处理不同的场景
# 3.option:设置一些基本参数,用来传输时限定
# 4.childHandler:核心处理器,这里创建一个ChannelInitializer,用来向管道里面注册其它handler,该ChannelInitializer会在添加进管道中后被删除
bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void ini
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的 Spring Boot 应用程序中使用 NettyServerBootstrap 和 Bootstrap 来创建服务器和客户端的示例: 1. 首先,需要在 Maven 中添加以下依赖项: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.65.Final</version> </dependency> ``` 2. 创建 Netty 服务器的代码: ```java @Component public class NettyServer { private final EventLoopGroup bossGroup = new NioEventLoopGroup(); private final EventLoopGroup workerGroup = new NioEventLoopGroup(); @Autowired private NettyServerInitializer nettyServerInitializer; public void start() throws InterruptedException { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(nettyServerInitializer); ChannelFuture future = bootstrap.bind(8080).sync(); future.channel().closeFuture().sync(); } @PreDestroy public void stop() { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } ``` 3. 创建 Netty 服务器的初始化器: ```java @Component public class NettyServerInitializer extends ChannelInitializer<SocketChannel> { @Autowired private NettyServerHandler nettyServerHandler; @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(nettyServerHandler); } } ``` 4. 创建 Netty 服务器的处理器: ```java @Component public class NettyServerHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) { // 处理接收到的数据 System.out.println("Received message: " + msg); ctx.writeAndFlush("Server response: " + msg); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 处理异常 cause.printStackTrace(); ctx.close(); } } ``` 5. 创建 Netty 客户端的代码: ```java @Component public class NettyClient { private final EventLoopGroup group = new NioEventLoopGroup(); @Autowired private NettyClientInitializer nettyClientInitializer; public String sendMessage(String host, int port, String message) throws InterruptedException, ExecutionException { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(nettyClientInitializer); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().writeAndFlush(message).sync(); future.channel().closeFuture().sync(); return nettyClientInitializer.getResponse(); } @PreDestroy public void stop() { group.shutdownGracefully(); } } ``` 6. 创建 Netty 客户端的初始化器: ```java @Component public class NettyClientInitializer extends ChannelInitializer<SocketChannel> { private String response; @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new StringEncoder(), new StringDecoder(), new NettyClientHandler(this)); } public String getResponse() { return response; } public void setResponse(String response) { this.response = response; } } ``` 7. 创建 Netty 客户端的处理器: ```java public class NettyClientHandler extends SimpleChannelInboundHandler<String> { private final NettyClientInitializer nettyClientInitializer; public NettyClientHandler(NettyClientInitializer nettyClientInitializer) { this.nettyClientInitializer = nettyClientInitializer; } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) { // 处理接收到的数据 nettyClientInitializer.setResponse(msg); ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 处理异常 cause.printStackTrace(); ctx.close(); } } ``` 在 Spring Boot 应用程序中使用 NettyServerBootstrap 和 Bootstrap 来创建服务器和客户端,需要将 Netty 服务器和客户端的 Bean 注入到 Spring 容器中,并在需要使用时使用它们。例如,在控制器中使用 Netty 客户端: ```java @RestController @RequestMapping("/netty") public class NettyController { @Autowired private NettyClient nettyClient; @GetMapping("/send") public String sendMessage() throws InterruptedException, ExecutionException { return nettyClient.sendMessage("localhost", 8080, "Hello from client"); } } ``` 这样,当访问 /netty/send 路径时,将会向 Netty 服务器发送消息并接收响应。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值