grpc源码阅读(go)

本文详细探讨了gRPC Go服务器的创建过程,包括`grpce.NewServer`的选项应用、服务注册`RegisterGreeterServer`以及服务器启动`s.Serve(lis)`。通过源码分析,揭示了从构建server、设置拦截器到处理请求的完整流程。
摘要由CSDN通过智能技术生成

server

func main() {
   
	lis, err := net.Listen("tcp", port)
	if err != nil {
   
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{
   })
	if err := s.Serve(lis); err != nil {
   
		log.Fatalf("failed to serve: %v", err)
	}
}

此处是grpc下example的例子,主要完成了三件事 new一个server和注册该server,和启动该server
下面将从这两个方面来阐述。

grpce.NewServer(…ServerOption)

// NewServer creates a gRPC server which has no service registered and has not
// started to accept requests yet.
func NewServer(opt ...ServerOption) *Server {
   
	opts := defaultServerOptions
	for _, o := range opt {
   
		o.apply(&opts)
	}
	s := &Server{
   
		lis:    make(map[net.Listener]bool),
		opts:   opts,
		conns:  make(map[transport.ServerTransport]bool),
		m:      make(map[string]*service),
		quit:   grpcsync.NewEvent(),
		done:   grpcsync.NewEvent(),
		czData: new(channelzData),
	}
	chainUnaryServerInterceptors(s)
	chainStreamServerInterceptors(s)
	s.cv = sync.NewCond(&s.mu)
	if EnableTracing {
   
		_, file, line, _ := runtime.Caller(1)
		s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
	}

	if channelz.IsOn() {
   
		s.channelzID = channelz.RegisterServer(&channelzServer{
   s}, "")
	}
	return s
}



此处主要完成以下几件事
(1)获取defaultServerOptions 遍历opts,其中serverOption是一个接口,只有一个方法apply,通过装饰器newFuncServerOption 将各类参数转为*funcServerOption类型(例如WriteBufferSize),其中funcServerOption仅包含一个参数
f func(*serverOptions),执行ServerOption的apply(*serverOptions)方法,也就是执行func (fdo *funcServerOption) apply(do *serverOptions),等于执行方法f。

// A ServerOption sets options such as credentials, codec and keepalive parameters, etc.
type ServerOption interface {
   
	apply(*serverOptions)
}

此处是serverOptions

type serverOptions struct {
   
	creds                 credentials.TransportCredentials //证书
	codec                 baseCodec //序列化和反序列化
	cp                    Compressor // 压缩接口
	dc                    Decompressor // 解压接口
	unaryInt              UnaryServerInterceptor  //一元拦截器
	streamInt             StreamServerInterceptor // 流拦截器
	chainUnaryInts        []UnaryServerInterceptor 
	chainStreamInts       []StreamServerInterceptor
	inTapHandle           tap.ServerInHandle
	statsHandler          stats.Handler
	maxConcurrentStreams  uint32  
	maxReceiveMessageSize int  //最大接收数据
	maxSendMessageSize    int  //最大发送数据
	unknownStreamDesc     *StreamDesc
	keepaliveParams       keepalive.ServerParameters // 长连接的server参数
	keepalivePolicy       keepalive.EnforcementPolicy
	initialWindowSize     int32 //初始化的windows大小 下限为64k 上限为2^31
	initialConnWindowSize int32 //初始化conn大小,一个conn有多个stream,等于上面的值*16,htt2的限制是大于0,默认一个连接有100个流,超过了就被拒绝
	writeBufferSize       int //写入缓冲大小
	readBufferSize        int //读入缓冲大小
	connectionTimeout     time.Duration  //连接超时时间 默认120s
	maxHeaderListSize     *uint32 //最大头部大小
	headerTableSize       *uint32
}

var defaultServerOptions = serverOptions{
   
	maxReceiveMessageSize: defaultServerMaxReceiveMessageSize,
  //1024 * 1024 * 4 默认4m
	maxSendMessageSize:    defaultServerMaxSendMessageSize, 
  // math.MaxInt32 其中 MaxInt32  = 1<<31 - 1
	connectionTimeout:     120 * time.Second,
	writeBufferSize:       defaultWriteBufSize, //defaultWriteBufSize = 32 * 1024
	readBufferSize:        defaultReadBufSize,
  //defaultReadBufSize  = 32 * 1024
}


type funcServerOption struct {
   
	f func(*serverOptions)
}

func (fdo *funcServerOption) apply(do *serverOptions) {
   
	fdo.f(do)
}

func newFuncServerOption(f func(*serverOptions)) *funcServerOption {
   
	return &funcServerOption{
   
		f: f,
	}
}


// WriteBufferSize determines how much data can be batched before doing a write on the wire.
// The corresponding memory allocation for this buffer will be twice the size to keep syscalls low.
// The default value for this buffer is 32KB.
// Zero will disable the write buffer such that each write will be on underlying connection.
// Note: A Send call may not directly translate to a write.
func WriteBufferSize
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值