golang实现grpc服务端与客户端
时间: 2023-10-04 07:14:05 浏览: 219
Golang_GogRPC到JSON代理生成器遵循gRPC HTTP规范.zip
首先,需要安装gRPC和protobuf。可以使用以下命令:
```
go get -u google.golang.org/grpc
go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go
```
接下来,我们需要定义protobuf文件,其中包含服务的RPC方法和消息格式,例如:
```
syntax = "proto3";
package myservice;
message Request {
string message = 1;
}
message Response {
string message = 1;
}
service MyService {
rpc SayHello(Request) returns (Response) {}
}
```
然后,使用以下命令将protobuf文件编译为Go代码:
```
protoc --go_out=plugins=grpc:. myservice.proto
```
这将生成myservice.pb.go文件。
接下来,我们需要实现gRPC服务端和客户端。以下是一个简单的示例:
服务端:
```
package main
import (
"log"
"net"
"google.golang.org/grpc"
pb "path/to/myservice"
)
type myServiceServer struct{}
func (s *myServiceServer) SayHello(ctx context.Context, req *pb.Request) (*pb.Response, error) {
log.Printf("Received message: %v", req.Message)
return &pb.Response{Message: "Hello " + req.Message}, nil
}
func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterMyServiceServer(s, &myServiceServer{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
```
客户端:
```
package main
import (
"log"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "path/to/myservice"
)
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("failed to connect: %v", err)
}
defer conn.Close()
c := pb.NewMyServiceClient(conn)
res, err := c.SayHello(context.Background(), &pb.Request{Message: "World"})
if err != nil {
log.Fatalf("failed to call SayHello: %v", err)
}
log.Printf("Response message: %v", res.Message)
}
```
运行服务端和客户端,即可进行gRPC通信。
阅读全文