ZBLOG

golang grpc client use gzip

To use gzip compression with golang grpc client, you need to enable it in the grpc.WithDefaultCallOptions function when creating your client connection. Here’s an example:

import (
	"compress/gzip"
	"context"
	"log"
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/encoding"
	pb "path/to/your/proto/package"
)

func main() {
	// create a dial option to enable gzip compression
	dialOption := grpc.WithDefaultCallOptions(grpc.UseCompressor(gzip.Name))

	// create a grpc client connection
	conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), dialOption)
	if err != nil {
		log.Fatalf("failed to connect to grpc server: %v", err)
	}
	defer conn.Close()

	// create a grpc client
	client := pb.NewYourServiceClient(conn)

	// make a request
	req := &pb.YourRequest{...}
	resp, err := client.YourMethod(context.Background(), req)
	if err != nil {
		log.Fatalf("failed to call YourMethod: %v", err)
	}
	...

}

In the above example, we created a dial option grpc.WithDefaultCallOptions(grpc.UseCompressor(gzip.Name)) to enable gzip compression for all RPC calls made through this connection. We then passed this dial option to grpc.Dial() function to create a grpc client connection.

Note that the grpc server also needs to support gzip compression for this to work. To enable server-side gzip compression, you can use the grpc.WithDefaultCallOptions(grpc.UseCompressor(gzip.Name)) option when creating your server instance.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=684

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?