内容参考:
项目结构-项目根目录trip:
go 1.16编写,开启modules,所以创建项目目录后初始化mod:
go mod init trip
生成go.mod
1.编写服务定义
syntax = "proto3";
package trip;
option go_package="trip/proto"; // 注意包名,c/s代码编码时import该包名
message helloRequest {
string name=1;
int64 id=2;
}
message helloResponse {
string res=1;
}
service helloService{
rpc sayHello(helloRequest)returns(helloResponse){}
}
2.生成服务代码
进入proto目录下
protoc -I=. --go_out=plugins=grpc:. hello.proto
go mod tidygo mod vendor -v
3.客户端代码
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"log"
hellopb "trip/proto"
)
func main() {
conn, err := grpc.Dial(":50052", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
client := hellopb.NewHelloServiceClient(conn)
res, err := client.SayHello(context.Background(), &hellopb.HelloRequest{Name: "bob123", Id: 1})
if err != nil {
log.Fatal(err)
}
fmt.Println(res)
}
4.服务端代码
greeter.go
package greeter
import (
"context"
"fmt"
hellopb "trip/proto"
)
type Service struct {}
func (*Service) SayHello(c context.Context, req *hellopb.HelloRequest) (*hellopb.HelloResponse, error) {
fmt.Println(req.Name, req.Id)
return &hellopb.HelloResponse{
Res: req.Name,
}, nil
}
服务端入口代码
package main
import (
"fmt"
"google.golang.org/grpc"
"net"
"trip/greeter"
pb "trip/proto"
)
const PORT = ":50052"
func main() {
fmt.Println("grpc serevr starting")
lis, err := net.Listen("tcp", PORT)
if err != nil {
panic(err)
}
s := grpc.NewServer()
pb.RegisterHelloServiceServer(s, &greeter.Service{})
err = s.Serve(lis)
if err != nil {
panic(err)
}
}
5.启动服务
先启动服务端,再启动客户端
go run main.go
go run grpc_client.go