学习 Netty 从零到掌握,从开始到完结的的系列项目。实现自己的聊天系统,跟着小西贝走进 Netty 世界。
在本场 Chat 中,会讲到如下内容:
- Netty 服务端和客户端的发送信息和接收信息。
适合人群:对 Netty 有兴趣的技术人员。
整合 Spring Boot + Netty 进行一个小白入门的第一个 Java 项目,可以作为毕设和学习项目的敲门砖。
项目的开头,创建项目以及添加相关的的依赖。接下来就把手交到我手里吧,跟着我一起走进 Netty。
创建 Maven 依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --></parent><dependencies> <!-- Netty 依赖 --> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.32.Final</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- protubuf --> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.5.1</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java-util --> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java-util</artifactId> <version>3.5.1</version> </dependency> <!-- https://mvnrepository.com/artifact/io.grpc/grpc-all --> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-all</artifactId> <version>1.11.0</version> </dependency></dependencies>
创建 Netty server 服务
why:在创建服务端,要明白为什么 EventLoopGroup 需要两个?
because:因为 Netty 线程模式,可以去网上找找资料,这类的资料百度。
它用到两个线程组 worKerGroup、bossGroup。
- 主线程主要用于接收 client 连接的接收,创建相关资源。
- 从线程主要用于处理通道的读写、解码、编码。
可以看下 ServerBootstrap 的 group 的方法,入参有两个方法,从方法名就可以看出父和子,如果线程