Netty-gRPC介绍和使用
转自:http://www.saily.top/2017/07/23/netty5/
gRPC
Define your service using Protocol Buffers, a powerful binary serialization toolset and language
gRPC是基于Protobuf开发的RPC框架,简化了protobuf的开发,提供了服务端和客户端网络交互这一块的代码。
Demo
照着https://grpc.io/docs/quickstart/java.html测试一下官方的Demo。
记得要把Update a gRPC service
部分做了。
gRPC整合Gradle与代码生成
https://github.com/grpc/grpc-java
这个是gRPC-java项目,先引入gRPC的依赖。
1
|
compile 'io.grpc:grpc-netty:1.4.0'
|
然后配置gradle的grpc插件
1
|
apply plugin: 'java'
|
后面直接用gradle的任务就可以生成代码了。
gRPC提供了3种传输层的实现
-
gRPC comes with three Transport implementations:
- The Netty-based transport is the main transport implementation based on Netty. It is for both the client and the server.
- The OkHttp-based transport is a lightweight transport based on OkHttp. It is mainly for use on Android and is for client only.
- The inProcess transport is for when a server is in the same process as the client. It is useful for testing.
https://github.com/google/protobuf-gradle-plugin
The Gradle plugin that compiles Protocol Buffer (aka. Protobuf) definition files (*.proto) in your project. There are two pieces of its job:
- It assembles the Protobuf Compiler (protoc) command line and use it to generate Java source files out of your proto files.
- It adds the generated Java source files to the input of the corresponding Java compilation unit (sourceSet in a Java project; variant in an Android project), so that they can be compiled along with your Java sources.
实战
配置好后,进行一个演示
在src/main/proto
新建一个文件Student.proto
gradle插件默认从src/main/proto
找proto源文件进行代码生成,这里有提到,而且这个路径的配置是可以修改的。
1
|
syntax = "proto3";
|
然后执行gradle generateProto
,生成的代码默认是放在/build
目录下,我们手动拷贝到src/main/java
。
实现代码
1
|
package com.sail.grpc;
|
服务器端
1
|
package com.sail.grpc;
|
客户端
1
|
package com.sail.grpc;
|
作者:习惯沉淀
如果文中有误或对本文有不同的见解,欢迎在评论区留言。
如果觉得文章对你有帮助,请点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
扫码关注一线码农的学习见闻与思考。
回复"大数据","微服务","架构师","面试总结",获取更多学习资源!