grpc: avoid allocations for each message (#1939)

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-08-18 16:24:11 +03:00
parent 5756f43f12
commit 4cb6fca7e9

34
grpc.go
View File

@ -8,6 +8,7 @@ import (
"net" "net"
"reflect" "reflect"
"strings" "strings"
"sync"
"sync/atomic" "sync/atomic"
"time" "time"
@ -25,8 +26,10 @@ import (
type grpcClient struct { type grpcClient struct {
opts client.Options opts client.Options
codecs map[string]encoding.Codec
pool *pool pool *pool
once atomic.Value once atomic.Value
sync.RWMutex
} }
func init() { func init() {
@ -301,18 +304,13 @@ func (g *grpcClient) maxSendMsgSizeValue() int {
} }
func (g *grpcClient) newGRPCCodec(contentType string) (encoding.Codec, error) { func (g *grpcClient) newGRPCCodec(contentType string) (encoding.Codec, error) {
codecs := make(map[string]encoding.Codec) g.RLock()
if g.opts.Context != nil { defer g.RUnlock()
if v := g.opts.Context.Value(codecsKey{}); v != nil {
codecs = v.(map[string]encoding.Codec) if c, ok := g.codecs[contentType]; ok {
}
}
if c, ok := codecs[contentType]; ok {
return wrapCodec{c}, nil
}
if c, ok := defaultGRPCCodecs[contentType]; ok {
return wrapCodec{c}, nil return wrapCodec{c}, nil
} }
return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType) return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType)
} }
@ -721,6 +719,22 @@ func newClient(opts ...client.Option) client.Client {
c = options.Wrappers[i-1](c) c = options.Wrappers[i-1](c)
} }
rc.codecs = make(map[string]encoding.Codec, len(defaultGRPCCodecs))
for k, v := range defaultGRPCCodecs {
rc.codecs[k] = v
}
var codecs map[string]encoding.Codec
if rc.opts.Context != nil {
if v := rc.opts.Context.Value(codecsKey{}); v != nil {
codecs = v.(map[string]encoding.Codec)
}
}
for k, v := range codecs {
rc.codecs[k] = v
}
return c return c
} }