Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable GRPC compression in Go

Tags:

go

grpc

I see some methods WithCompression and UseCompression but I'm not very clear how they all fit together - a simple example of what to put in the client and what to put in the server would really help.

My first attempt,

conn, err := grpc.Dial(
    addr,
    grpc.WithTimeout(timeout),
    grpc.WithCompressor(grpc.NewGZIPCompressor()),
    ...

resulted in this error when I made a call:

grpc: Decompressor is not installed for grpc-encoding \"gzip\"
like image 408
Bryan Avatar asked Jan 09 '18 16:01

Bryan


People also ask

Does gRPC support compression?

The compression supported by gRPC acts at the individual message level, taking message as defined in the wire formatdocument". The implementation supports different compression algorithms. A default compression level, to be used in the absence of message-specific settings, MAY be specified for during channel creation.

What is gRPC compression?

gRPC offers lossless compression options in order to decrease the number of bits transferred over the wire. Three levels of compression are available: grpc.


2 Answers

grpc.WithCompressor as DialOption is deprecated, according to the docs.

You can use the grpc.UseCompressor(gzip.Name) CallOption, which operates at call level

var opts []grpc.CallOption
opts = append(callOptions, grpc.UseCompressor(gzip.Name))
opts = append(callOptions, ...)
opts = append(callOptions, ...)

err := grpc.Invoke(mycontext, "/myRpcFuntion", myInput, myOutput, myGrpcConn, opts...)

You do not need to call RegisterCompressor. The gzip package import does it for you in the init() function

func init() {
    c := &compressor{}
    c.poolCompressor.New = func() interface{} {
        return &writer{Writer: gzip.NewWriter(ioutil.Discard), pool: &c.poolCompressor}
    }
    encoding.RegisterCompressor(c)
}

At the server side, you need to import the gzip package to make sure that the gzip compressor is registered.

import _ "google.golang.org/grpc/encoding/gzip"
like image 67
cvigo Avatar answered Sep 19 '22 00:09

cvigo


Doc on the compression APIs can be find at: https://github.com/grpc/grpc-go/blob/master/Documentation/compression.md

like image 35
menghanl Avatar answered Sep 18 '22 00:09

menghanl