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