vlambda博客
学习文章列表

NodeJS gRPC如何启用压缩

在Node项目里调用gRPC时,发现默认没有启用gzip压缩,额的神这能忍😁?嗖嗖寻章摘句老雕虫,谷神也没找到,咋办呢,

手撸源码了,哎,拔剑四顾心茫然......     海量海量   偶然发现Node版本的gRPC 客户端的UA是:

grpc-node/1.24.2 grpc-c/8.0.0 (osx; chttp2; ganges)

看来像是包装了C语言版本gRPC的客户端,发现代码里确实是用的

C-based Client and Serverhttps://github.com/grpc/grpc-node

于是找到C代码,找到了解决方案,具体代码在这里:

https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/compression_types.h 

typedef enum { GRPC_COMPRESS_NONE = 0, GRPC_COMPRESS_DEFLATE, GRPC_COMPRESS_GZIP, /* EXPERIMENTAL: Stream compression is currently experimental. */ GRPC_COMPRESS_STREAM_GZIP, /* TODO(ctiller): snappy */ GRPC_COMPRESS_ALGORITHMS_COUNT} grpc_compression_algorithm;
typedef enum { GRPC_COMPRESS_LEVEL_NONE = 0, GRPC_COMPRESS_LEVEL_LOW, GRPC_COMPRESS_LEVEL_MED, GRPC_COMPRESS_LEVEL_HIGH, GRPC_COMPRESS_LEVEL_COUNT} grpc_compression_level;


因为我用的gzip,在创建gRPC客户端时传入两个变量:

 'grpc.default_compression_algorithm': 2,  'grpc.default_compression_level'2


Node代码完整如下:


const values = [208402197];const version ='1.1.0';const request = {interfaceName:'com.example.PersonServiceApi', version: version, //group :'',        method:'getOne', types :['long'], values:JSON.stringify(values)};
const PROTO_PATH = __dirname + '/clazz_method_param.proto';
const grpc = require('grpc');const protoLoader = require('@grpc/proto-loader');const packageDefinition = protoLoader.loadSync( PROTO_PATH, {keepCase: true, longs: String, enums: String, defaults: true, oneofs: true });const dubbo = grpc.loadPackageDefinition(packageDefinition).dubbo;
// https://github.com/grpc/grpc/blob/master/examples/node/dynamic_codegen/greeter_client.jsconst client = new dubbo.ProxyService('grpc.internal.example.com:5050', grpc.credentials.createInsecure(), { 'grpc.default_compression_algorithm': 2, 'grpc.default_compression_level': 2});client.InvokeProxy(request, function(err, response) { console.log('result:', response); });


打完收工快乐去睡觉了。