1. 下载工具

如果觉得下载较慢可以点击这里下载:
protoc-21.3-linux-x86_64.zip
protoc-21.3-win64.zip
下载完成后解压后记得将路径添加到环境变量中

2. 下载go的依赖包

  1. go get github.com/golang/protobuf/protoc-gen-go

3. proto文件

  1. syntax = "proto3";
  2. option go_package = ".;proto";
  3. service Greeter {
  4. rpc SayHello (HelloRequest) returns (HelloReply);
  5. }
  6. message HelloRequest {
  7. string name = 1;
  8. }
  9. message HelloReply {
  10. string message = 1;
  11. }

4. 生成go文件

  1. protoc -I . helloworld.proto --go_out=plugins=grpc:.

5. 服务端代码

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "google.golang.org/grpc"
  6. "grpc_demo/hello"
  7. "net"
  8. )
  9. type Server struct {
  10. }
  11. func (s *Server) SayHello(ctx context.Context,request *hello.HelloRequest)(*hello.HelloReply,error){
  12. return &hello.HelloReply{Message:"Hello "+request.Name},nil
  13. }
  14. func main() {
  15. g := grpc.NewServer()
  16. s := Server{}
  17. hello.RegisterGreeterServer(g,&s)
  18. lis, err := net.Listen("tcp", fmt.Sprintf(":8080"))
  19. if err != nil {
  20. panic("failed to listen: "+err.Error())
  21. }
  22. g.Serve(lis)
  23. }

6. 客户端

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "google.golang.org/grpc"
  6. "grpc_demo/proto"
  7. )
  8. func main() {
  9. conn,err := grpc.Dial("127.0.0.1:8080",grpc.WithInsecure())
  10. if err!=nil{
  11. panic(err)
  12. }
  13. defer conn.Close()
  14. c := hello.NewGreeterClient(conn)
  15. r,err := c.SayHello(context.Background(),&hello.HelloRequest{Name:"bobby"})
  16. if err!=nil{
  17. panic(err)
  18. }
  19. fmt.Println(r.Message)
  20. }