Google高性能开源框架gRPC:快速搭建及HTTP/2抓包

一、什么是gRPC

gRPC是google发起的一个*远程过程调用(rpc)*开源框架,可以在任何语言中,用任何编程语言编写。gRPC基于HTTP/2协议,使用Protocol Buffers作为序列化工具。

gRPC官网:https://grpc.io/

RPC

Remote Procedure Call,远程过程调用协议,一种通过网络调用远程计算机上服务,并且无需关注交互细节。可以理解为,服务A调用另一个服务B中的某段程序,底层实现对于开发者无感知,可以是基于HTTP/1.1也可以基于HTTP/2,可以序列化成json,xml,Protocol Buffers这些都不需要关心。像Dubbo就是一个RPC框架,仅关心业务编程即可。

Protocol Buffers

Protocol Buffers是一个跨语言,跨平台可扩展的数据结构序列化的一个工具语言,和JSON类似,但比JSON更小,更高效。需要通过工具编译成指定语言的代码,相当于你定义的对象需要由工具生成。

HTTP/2

HTTP协议第二个版本,兼容HTTP/1.1(目前广泛使用的仍然是HTTP/1.1),基于SPDY协议,于2015年2月17日被批准。

特性如下:

  1. 头部压缩:使用HPACK算法对头部进行压缩
  2. 对数据传输采用多路复用,让多个请求合并在同一TCP连接内。
  3. 服务端主动推送消息

二、简单实践

文件生成

因为gRPC基于Protocol Buffers,需要通过工具来生成。

一种完全无依赖的方式是自己下载软件,如果要使用gRPC需要额外下载protoc-gen-grpc-java

proto地址:https://github.com/protocolbuffers/protobuf/releases/tag/v24.3

protoc-gen-grpc-java地址:https://repo.maven.apache.org/maven2/io/grpc/protoc-gen-grpc-java/1.58.0/

配置了好久没有配置成功,然后用了其他方案,maven插件的方式

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.21.5:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.48.1:exe:${os.detected.classifier}</pluginArtifact>
                    <protoSourceRoot>${project.basedir}/src/main/proto</protoSourceRoot>
                    <!-- 生成的Java文件目录 -->
                    <outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
                    <clearOutputDirectory>false</clearOutputDirectory>

                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>

服务端实现

生成的文件部分就不占用过多篇幅了

仓库地址:https://gitee.com/Nortyr/allinone

这个是服务端实现,其中doubleStream我测试接收stream,返回stream

public class ServiceImpl extends GreeterGrpc.GreeterImplBase{
  //...略
    @Override
    public StreamObserver<Helloworld.HelloRequest> doubleStream(StreamObserver<Helloworld.HelloReply> responseObserver) {
        return new StreamObserver<Helloworld.HelloRequest>() {
            AtomicInteger integer=new AtomicInteger();

            @Override
            public void onNext(Helloworld.HelloRequest helloRequest) {
                System.out.println(helloRequest.getMessage());

                Helloworld.HelloReply response = Helloworld.HelloReply.newBuilder()
                        .setMessage("瞅你咋地~~"+integer.incrementAndGet())
                        .build();
                responseObserver.onNext(response);
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("error: " + throwable.getMessage());

            }

            @Override
            public void onCompleted() {
                System.out.println("Server completed");
                responseObserver.onCompleted();
            }
        };
    }
}
  • 服务端代码:
public class ServerDemo {
    public static void main(String[] args) throws Exception {
        int port = 9091;
        Server server = ServerBuilder
                .forPort(port)
                .addService(new ServiceImpl())
                .build()
                .start();
        System.out.println("server started, port : " + port);
        server.awaitTermination();
    }
}
  • 客户端代码:
 private static void testDoubleStream() throws InterruptedException {
        String host = "127.0.0.1";
        int port = 9091;
        ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build();

//        client接收一个对象
        GreeterGrpc.GreeterStub stub = GreeterGrpc.newStub(channel);


        StreamObserver<Helloworld.HelloRequest> doubleStream = stub.doubleStream(new StreamObserver<Helloworld.HelloReply>() {

            @Override
            public void onNext(Helloworld.HelloReply helloReply) {
                System.out.println("Received: " + helloReply.getMessage());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("error: " + throwable);
            }

            @Override
            public void onCompleted() {
                System.out.println("Client completed");
            }
        });
        doubleStream.onNext(Helloworld.HelloRequest.newBuilder().setMessage("你瞅啥~~ 1").build());
        doubleStream.onNext(Helloworld.HelloRequest.newBuilder().setMessage("你瞅啥~~ 2").build());
        doubleStream.onNext(Helloworld.HelloRequest.newBuilder().setMessage("你瞅啥~~ 3").build());
        doubleStream.onCompleted();
        Thread.sleep(10000);
        channel.shutdown();
    }
  • 启动结果如下:

抓包分析

还没见过HTTP/2报文,想看下,发现全是TCP

需要修改下,使用http2解析

如果想要看到内容需要配置下ProtoBuf文件位置
Wireshark>Perferences>Protocols>ProtoBuf

至此over~~~

结尾

  • 仓库地址:https://gitee.com/Nortyr/allinone/tree/main/grpc_demo
  • 参考资料
    • https://grpc.io/
    • https://protobuf.dev/
    • https://zh.wikipedia.org/wiki/HTTP/2
    • https://blog.csdn.net/luo15242208310/article/details/122909827
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 gRPC 的 C++ API 中的 `grpc::ServerBuilder` 构建 gRPC 服务器的一个简单示例: ```cpp #include <iostream> #include <memory> #include <string> #include <grpcpp/grpcpp.h> #include "greeter.grpc.pb.h" using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::Status; using helloworld::Greeter; using helloworld::HelloReply; using helloworld::HelloRequest; // 实现 Greeter 服务 class GreeterServiceImpl final : public Greeter::Service { Status SayHello(ServerContext* context, const HelloRequest* request, HelloReply* reply) override { std::string prefix("Hello "); reply->set_message(prefix + request->name()); return Status::OK; } }; void RunServer() { std::string server_address("0.0.0.0:50051"); GreeterServiceImpl service; // 创建 ServerBuilder 对象并指定服务器地址 ServerBuilder builder; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); // 将 Greeter 服务添加到 gRPC 服务器中 builder.RegisterService(&service); // 构建服务器并启动 std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; // 等待服务器关闭 server->Wait(); } int main(int argc, char** argv) { RunServer(); return 0; } ``` 在上面的示例中,我们首先实现了 `Greeter::Service`,并在其中实现了 `SayHello` 方法。然后,我们创建了一个 `GreeterServiceImpl` 对象,并将其注册到 `ServerBuilder` 中,使用 `AddListeningPort` 方法指定服务器地址和安全凭证,最后使用 `BuildAndStart` 方法构建 gRPC 服务器并启动。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值