Go微服务实战|第8章:gRPC Cancelling RPCs

  • 原创
  • Madman
  • /
  • /
  • 0
  • 4043 次阅读

Go 微服务实战.png

Synopsis: 本文演示了客户端和服务端建立了双向流之后,双方都可以不断地向对方发送或接收数据,如果客户端不想再连接了,它主动调用 cancel() 方法,将会取消 context 上下文,即关闭双向流,那么服务端会立即收到 codes.Canceled 错误状态码。同时,如果之后客户端再次想从双向流中发送或读取数据,都会收到 codes.Canceled 错误状态码

代码已上传到 https://github.com/wangy8961/grpc-go-tutorial/tree/v0.8 ,欢迎 star

1. 双向流 RPC

创建 grpc-go-tutorial/features/cancel/server/main.go 文件:

// Package main implements a server for Echo service.
package main

import (
    "context"
    "flag"
    "fmt"
    "io"
    "log"
    "net"

    pb "github.com/wangy8961/grpc-go-tutorial/features/echopb"
    "google.golang.org/grpc"
    "google.golang.org/grpc/codes"
    "google.golang.org/grpc/status"
)

// server is used to implement echopb.EchoServer.
type server struct{}

func (s *server) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
    return nil, status.Errorf(codes.Unimplemented, "method UnaryEcho not implemented")
}

func (s *server) ServerStreamingEcho(req *pb.EchoRequest, stream pb.Echo_ServerStreamingEchoServer) error {
    return status.Errorf(codes.Unimplemented, "method ServerStreamingEcho not implemented")
}

func (s *server) ClientStreamingEcho(stream pb.Echo_ClientStreamingEchoServer) error {
    return status.Errorf(codes.Unimplemented, "method ClientStreamingEcho not implemented")
}

func (s *server) BidirectionalStreamingEcho(stream pb.Echo_BidirectionalStreamingEchoServer) error {
    for {
        in, err := stream.Recv()
        if err != nil {
            fmt.Printf("server: error receiving from stream: %v\n", err)
            if err == io.EOF {
                return nil
            }
            return err
        }
        fmt.Printf("echoing message %q\n", in.Message)
        stream.Send(&pb.EchoResponse{Message: in.Message})
    }
}

func main() {
    port := flag.Int("port", 50051, "the port to serve on")
    flag.Parse()

    lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *
                                
                            
  • blake
  • 42952091
  • 31787219
  • chenfan
  • 32445059
  • voidnil0
  • fissh
  • 38198038
  • sailing
  • 2962285897
  • 49666436
  • henry
  • 47849342
  • tomy113
  • 39613212
  • john
  • mikey
  • 29811707
  • kang-zhu-kang-zhu-kang-zhu
  • qzj1900
  • ttttjjjj2008
  • twba-xiaomi
  • ssc-zcys
  • 22450935
未经允许不得转载: LIFE & SHARE - 王颜公子 » Go微服务实战|第8章:gRPC Cancelling RPCs

分享

作者

作者头像

Madman

如需 Linux / Python 相关问题付费解答,请按如下方式联系我

0 条评论

暂时还没有评论.

专题系列