Bryan
Bryan

Reputation: 12190

How to enable GRPC compression in Go

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\"

Upvotes: 8

Views: 11049

Answers (2)

cvigo
cvigo

Reputation: 415

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"

Upvotes: 12

menghanl
menghanl

Reputation: 771

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

Upvotes: 2

Related Questions