,
一月 16, 2023 8:00:13 下午 ken.grpc.examples.helloworld.HelloWorldClient greet
INFO: Will try to greet world1 ...
一月 16, 2023 8:00:13 下午 ken.grpc.examples.helloworld.HelloWorldClient greet
INFO: Greeting: Hello 1world1
就可以在客户端看到对应的调用。
Go语言客户端
首先按照https://grpc.io/docs/languages/go/quickstart/里面的Prerequisites安装go, 下载Protocol buffer 编译器, protoc,文档里面的是Linux的指引,我用的是Window的系统,所以要下载到对应的Window版本,然后配置到Path里面。参考了这篇文章
https://www.geeksforgeeks.org/how-to-install-protocol-buffers-on-windows/
https://github.com/protocolbuffers/protobuf/releases/tag/v21.12
执行命令
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
安装插件。
基本的环境就可以了,就可以编码了。
首先用go mod init grpcdemo/hello新建一个项目
然后和Java相同的添加.proto文件,这里需要在proto文件中添加一行
option go_package = "grpcdemo/hello/helloworld";
这样才可以生成go语言的类,执行命令
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative helloworld/helloworld.proto
我们可以在目录下面看到生成的类
然后编写grpc-client/main.go,这里代码也是复制example里面的代码
https://github.com/grpc/grpc-go/blob/master/examples/helloworld/greeter_client/main.go
需要修改的地方是引用的包修改成你自己的
pb "grpcdemo/hello/helloworld/helloworld"
运行这个main.go,控制台输出
2023/01/16 16:18:31 Greeting: Hello 1world
我们调用了Java服务端的服务使用GO语言。
总结
体验gRPC整体感觉还是很容易,不管是服务端还是客户端都是以proto文件作为协议的基础, 查了下实际的引用中,这个文件的存放位置也比较有它的方法。这里有篇文章专门说这个事情https://blog.csdn.net/kevin_tech/article/details/122834090
如何编写proto,如何写好grpc的代码还有很多需要学习,这里只是体验一下,暂未深入。后期继续在深入学习一下。 同时也打算做些对比试验,比如它跟rest服务对比下到底能快多少,和Dubbo对比一下,哪个更好用。