1.创建 .proto文件
syntax = "proto3";
option go_package="../;helloproto"; // 生成pb文件的存放位子 ../ 上一级目录
package helloworld;
service Helloserver {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
2.代码生成命令
protoc --go_out=./ ./hello.proto
protoc --go-grpc_out=./ hello.proto
前提条件是必须下载protoc.exe和protoc-gen-go.exe 并且加入环境变量
代码生成后的样子
有两个pb.go结尾的文件
需要提前安装 net 库
cannot find package “golang.org/x/net/http2“_Bug制造者-CSDN博客(安装流程)
3.代码
service代码:
package main
import (
"context"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"log"
"net"
pb "protobuf/grpc/hello"
)
type Helloserver struct {
pb.UnimplementedHelloserverServer
}
func(this *Helloserver)SayHello(ctx context.Context, in *pb.HelloRequest) (out *pb.HelloReply, err error){
return &pb.HelloReply{
Message: "hello grpc ===> " + in.Name,
},nil
}
func main() {
lis, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer() // 创建grpc服务
pb.RegisterHelloserverServer(s, &Helloserver{})
// Register reflection service on gRPC server.
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
client
package main
import (
"context"
"log"
"google.golang.org/grpc"
pb "protobuf/grpc/hello"
)
const (
address = "127.0.0.1:8080"
)
func main() {
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatalf("客户端连接异常: %v", err)
}
defer conn.Close()
c := pb.NewHelloserverClient(conn)//获取GRPC句柄
r, err := c.SayHello(context.Background(), &pb.HelloRequest{
Name: "哈哈",
})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("####### get server Greeting response: %s", r.Message)
}
go run grpc_server.go
go run grpc_client.go