阅读 127

grpc调用protobuf生成的文件

grpc调用protobuf生成的文件

记录下protoc生成go文件后,使用grpc调用的过程

  • grpc安装

 go get -u -v google.golang.org/grpc 

  • server.go

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
 
import (
    "context"
    "fmt"
    "google.golang.org/grpc"
    "net"
    "rpc/student"
    "strconv"
)
 
type Stu struct {
 
}
 
func (s Stu) GetInfo (ctx context.Context, req *student.StuReq) (*student.Student, error){
 
    student := student.Student{
        Score: 10,
        P:     &student.Person{
            Name: "hello"+ strconv.Itoa(int(req.Id)),
            Sex:  0,
        },
        Like:  []string{
            "football",
            "sport",
        },
    }
 
    return &student,nil
}
 
func main(){
 
    grpcServer := grpc.NewServer()
 
    student.RegisterStuServiceServer(grpcServer,new(Stu))
 
    listen,err := net.Listen("tcp","127.0.0.1:8082")
    if err != nil{
        fmt.Println(err)
    }
    defer listen.Close()
 
    grpcServer.Serve(listen)
 
}
  • client.go

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"
    "rpc/student"
)
 
func main(){
 
    client,err := grpc.Dial("127.0.0.1:8082",grpc.WithInsecure())
    if err != nil{
        fmt.Println(err)
    }
    defer client.Close()
 
    stuClient := student.NewStuServiceClient(client)
 
    stuReq := student.StuReq{Id:1}
 
    stu,err := stuClient.GetInfo(context.TODO(),&stuReq)
    if err != nil{
        fmt.Println(err)
    }
 
    fmt.Println(stu)
}

  

来源https://www.cnblogs.com/itsuibi/p/14727186.html

文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐