一个实际的例子
文件目录
F:.
│ Gen_proto.bat
│ go.mod
│ go.sum
│
├─client
│ client.go
│
├─pb
│ user.pb.go
│ user.proto
│ user_grpc.pb.go
│
└─server
server.go
定义proto文件
syntax="proto3";
package pb;
option go_package = ".;pb";
message UserRequest{
string name = 1;
}
message UserResponse{
int32 id = 1;
string name = 2;
int32 age =3;
repeated string hobby = 4;
}
message TaskRequest{
string name = 1;
}
service UserInfoService{
rpc GetUserInfo (UserRequest) returns (UserResponse){}
rpc GetTaskInfo (TaskRequest) returns (UserResponse){}
}
执行生成proto的命令
protoc --go_out=.\pb .\pb\user.proto
protoc --go-grpc_out=require_unimplemented_servers=false:.\pb .\pb\user.proto
不加 require_unimplemented_servers=false 会多生成 mustEmbedUnimplementedUserInfoServiceServer
type UserInfoServiceServer interface {
GetUserInfo(context.Context, *UserRequest) (*UserResponse, error)
GetTaskInfo(context.Context, *TaskRequest) (*UserResponse, error)
mustEmbedUnimplementedUserInfoServiceServer()
}
Server端代码
package main
import (
"context"
"demo-grpc/pb"
"fmt"
"log"
"net"
"google.golang.org/grpc"
)
type UserInfoService struct {
}
var u = UserInfoService{}
func (s *UserInfoService) GetUserInfo(ctx context.Context, req *pb.UserRequest) (resp *pb.UserResponse, err error) {
name := req.Name
resp = &pb.UserResponse{
Name: fmt.Sprintf("UserReq %v ", name),
}
err = nil
return
}
func (s *UserInfoService) GetTaskInfo(ctx context.Context, req *pb.TaskRequest) (resp *pb.UserResponse, err error) {
name := req.Name
resp = &pb.UserResponse{
Name: fmt.Sprintf("TaskReq %v ", name),
}
err = nil
return
}
func main() {
addr := "127.0.0.1:8080"
lis, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
// b = pb.ProtoServiceServer{}
pb.RegisterUserInfoServiceServer(s, &u)
s.Serve(lis)
}
Client 端代码
package main
import (
"context"
"demo-grpc/pb"
"fmt"
"log"
"google.golang.org/grpc"
)
func main() {
serverAddr := "127.0.0.1:8080"
// var opts []grpc.DialOption
conn, err := grpc.Dial(serverAddr, grpc.WithInsecure())
if err != nil {
log.Fatalf("fail to dial: %v", err)
}
defer conn.Close()
client := pb.NewUserInfoServiceClient(conn)
req := new(pb.UserRequest)
req.Name = "User_Info"
resp, err := client.GetUserInfo(context.Background(), req)
if err != nil {
fmt.Printf("GetUserInfo err %v", err)
}
fmt.Printf("UserInfo %v \n", resp.Name)
req2 := &pb.TaskRequest{
Name: "Task",
}
resp, err = client.GetTaskInfo(context.Background(), req2)
if err != nil {
fmt.Printf("GetTaskInfo err %v", err)
}
fmt.Printf("TaskInfo %v \n", resp.Name)
}