前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >grpc调用protobuf生成的文件

grpc调用protobuf生成的文件

作者头像
码缘
发布2021-05-07 16:07:20
5580
发布2021-05-07 16:07:20
举报
文章被收录于专栏:PHP修行之路PHP修行之路

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

  • grpc安装

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

  • server.go
代码语言:javascript
复制
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
代码语言:javascript
复制
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)
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-05-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档