go集成grpc

go集成grpc,第1张

go集成grpc 一,准备条件 1.1 下载protoc.exe

可以去 https://github.com/protocolbuffers/protobuf 下载

1.2 下载protoc-gen-go.exe

通过命令 go install google.golang.org/protobuf/cmd/[email protected] 得到

1.3 下载protoc-gen-go-grpc.exe

通过命令 go install google.golang.org/grpc/cmd/[email protected] 得到

1.4 总结

grpc参考官网 https://www.grpc.io/。把这些exe文件都加到环境变量

二,项目 2.1 编写proto文件
syntax = "proto3";

package service;

option go_package = "go-test/pb/hello;hello";

message Req{
  int32 prod_id=1;
}

message Res{
  int32 prod_stock=1;
}

service Hello{
  rpc Hello(Req) returns (Res);
}
2.2 执行命令
//go:generate protoc --go_out=. --go_opt=paths=source_relative   --go-grpc_out=. --go-grpc_opt=paths=source_relative     ./pb/hello.proto

2.3 编写server
//生成或者更新 proto的go代码
//go:generate protoc --go_out=. --go_opt=paths=source_relative   --go-grpc_out=. --go-grpc_opt=paths=source_relative     ./pb/hello.proto

func main()  {
	startServer()
}



func startServer(){
	l, err := net.Listen("tcp", ":9999")
	if err != nil{
		panic(err)
	}
	s := grpc.NewServer()
	hello.RegisterHelloServer(s,&rpcServer{})
	s.Serve(l)
}

type  rpcServer struct{
	hello.UnimplementedHelloServer
}

func (r *rpcServer) Hello(ctx context.Context,req *hello.Req) (res *hello.Res,err error){
	res = &hello.Res{ProdStock: 99}
	return res,nil
}
2.4 编写client测试类
//测试 提供的服务
func TestClient(t *testing.T) {
	log.Println("开始启动客户端")
	conn, err := grpc.Dial("localhost:9999",grpc.WithInsecure())
	if err !=nil{
		log.Fatalln(err)
	}
	defer conn.Close()
	client := hello.NewHelloClient(conn)
	res, err := client.Hello(context.Background(), &hello.Req{ProdId: 1})

	if err != nil{
		log.Fatalln(err)
	}

	fmt.Println(res)

}
2.5 大功告成,打道回府

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/990904.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存