go语言下的grpc开发
1、下载protoc
地址:https:
//github.com/google/protobuf/releases
window:
下载: protoc-3.3.0-win32.zip
解压,把bin目录下的protoc.exe复制到GOPATH/bin下,GOPATH/bin加入环境变量。
当然也可放在其他目录,需加入环境变量,能让系统找到protoc.exe
linux:
下载:protoc-3.3.0-linux-x86_64.zip 或 protoc-3.3.0-linux-x86_32.zip
解压,把bin目录下的protoc复制到GOPATH/bin下,GOPATH/bin加入环境变量。
如果喜欢编译安装的,也可下载源码自行安装,最后将可执行文件加入环境变量。
2、下载go的依赖包
命令:go get -u github.com/golang/protobuf/protoc-gen-go
3、创建protoc文件
goland安装proto support插件教程:(29条消息) Gland安装 protobuf Support 插件_劉小五的博客-CSDN博客_goland protobuf support
4、生成go文件
参考:(29条消息) golang_protoc: protoc编译生成pb.go文件_Grayan的博客-CSDN博客_protoc 生成pb文件
proto文件内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | syntax = "proto3" ; package hello; option go_package = ".;proto" ; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; } |
生成命令改为:protoc -I . hello.proto --go_out=plugins=grpc:.
5、代码
服务端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package main import ( "context" "fmt" "google.golang.org/grpc" "server/proto" "net" ) type Server struct { } func (s *Server) SayHello(ctx context.Context,request *proto.HelloRequest)(*proto.HelloReply,error){ return &proto.HelloReply{Message: "Hello " +request.Name},nil } func main() { g := grpc.NewServer() s := Server{} proto.RegisterGreeterServer(g,&s) lis, err := net.Listen( "tcp" , fmt.Sprintf( ":8080" )) if err != nil { panic( "failed to listen: " +err.Error()) } g.Serve(lis) } |
客户端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package main import ( "context" "fmt" "google.golang.org/grpc" "client/proto" ) func main() { conn,err := grpc.Dial( "127.0.0.1:8080" ,grpc.WithInsecure()) if err!=nil{ panic(err) } defer conn.Close() c := proto.NewGreeterClient(conn) r,err := c.SayHello(context.Background(),&proto.HelloRequest{Name: "bobby" }) if err!=nil{ panic(err) } fmt.Println(r.Message) } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
2021-04-26 Android Studio学习笔记