At work, the original Java server-based SPRINGMVC service is changed to be called directly using GRPC. Because the return value of the original service is a dynamic map type, the key value is indeterminate and the type of value is not unique, so the map and any types in Protobuf 3 are used. In this process encountered some difficulties, access to information found that this piece of information is not a lot, especially in the Nodejs grpc-client processing google.protobuf.Any type, completely can not find the relevant information. Fortunately, after groping and debugging, the problem is solved, so it is recorded for others ' needs.
Testservice.proto:
1Syntax ="Proto3";2 3Import"Google/protobuf/any.proto";4Option Java_package ="Com.zfp.demo.grpc";5 6 service Testservice {7 RPC Getmapdata (Param) returns (Genericmap);8 }9 Ten message Genericmap { Onemap<string, google.protobuf.any> value =1; A } - - message param{ the stringValue =1; - } - - message listparam{ +RepeatedstringValue =1; -}
Where the any type does not need to explicitly define the structure and type of the value in Protobuf, but rather to package any message into any type via pack () on the server side of GRPC (it is not possible to package Java Object directly). The client can remove the message from any by unpack (), enabling the Protobuf to support generics.
Java Server:
1 ImportCom.google.protobuf.Any;
2@Overried3 Public voidGetmapdata (Testservice.param request, streamobserver<testservice.genericmap>responseobserver) {4 5Testservice.param stringvalue =Testservice.param6 . Newbuilder ()7. SetValue ("This is a String type")8 . Build ();9 Tenlist<string> templist = Lists.newarraylist ("This is", "List type"); OneTestservice.listparam ListValue =Testservice.listparam A . Newbuilder () - . Addallvalue () - . Build (); the -map<string, any> ReMap =Maps.newhashmap (); -Remap.put ("K1", Any.pack (stringvalue)); -Remap.put ("K2", Any.pack (ListValue)); + -Testservice.genericmap Genericmap =Testservice.genericmap +. Newbuilder () A . Putallvalue (REMAP) at . Build (); - - Responseobserver.onnext (genericmap); - responseobserver.oncompleted (); -}
Java Client:
1 @Test2 Public voidGetmapdatatest ()throwsexecutionexception, interruptedexception {3 4Managedchannel channel = managedchannelbuilder.foraddress ("127.0.0.1", 6565)5. Useplaintext (true)6 . Build ();7 8Testservicegrpc.roomserviceblockingstub bkstub =testservicegrpc.newblockingstub (channel);9 Ten OneTestservice.param Param = Testservice.Param.newBuilder (). SetValue ("Test Param"). Build (); A -map<string, any> ReMap =bkstub.getmapdata (param). Get (). Getvaluemap (); - themap<string, object> DataMap =Maps.newhashmap (); - -Remap.foreach (k, v) { - if(K.equals ("K1")) { + Try { -Datamap.put (k, V.unpack (Testservice.param).class). GetValue ()); +}Catch(invalidprotocolbufferexception e) { A e.printstacktrace (); at } -}Else { - Try { -Datamap.put (k, V.unpack (Testservice.listparam).class). Getvaluelist ()); -}Catch(invalidprotocolbufferexception e) { - e.printstacktrace (); in } - } to }); + -Logger.info (Json.tojsonstring (DataMap,true)); the}
NodeJS Client:
varMessages = require ('./TESTSERVICE_PB '));varServices = require ('./TESTSERVICE_GRPC_PB ')); //These two files are automatically generated using the PROTOC command according to Testservice.proto varGRPC = require (' Grpc '));varProb = require ('./NODE_MODULES/GOOGLE-PROTOBUF/GOOGLE/PROTOBUF/ANY_PB ')); //Use of any type must be introduced into this file varJSPB = require (' Google-protobuf ')); main=function () { varClient =NewServices. Testserviceclient (' localhost:6565 ', Grpc.credentials.createInsecure ()); varRequest =Newmessages. Param ();request.setvalue ("Test param"); Client.getmapdata (Request,function(Err, res) {varReMap =Unpackgpmap (RES); Console.log (REMAP); });};/** * Unpack the Google.protobuf.Any object and return the result * @param {!google.protobuf.any} gpany*/Unpackany=function(gpany) {varTypeName =Gpany.gettypename (); Gets the type name of the message object for the any wrappervardeserialize; Switch(typeName) { Case"Listparam": Deserialize=messages. Listparam.deserializebinary; Deserializing the function of Listparam from Uint8arrayreturnunpackany_list (Gpany, deserialize, typeName); Case"Param": Deserialize=messages. Param.deserializebinary; returnUnpackany_onefield (Gpany, deserialize, typeName); Case"Objparam": Deserialize=messages. Objparam.deserializebinary; returnUnpackany_complexobject (Gpany, deserialize, typeName); default: return"The Message type \ '" + typeName + "\ ' is not defiend in. proto File"; }};
/**
* Any wrapped message containing only one field named value is used
*/Unpackany_onefield=function(Gpany, deserialize, typeName) {returnGpany.unpack (Deserialize, typeName). Toobject () ["Value"];}; /**
* Any wrapped message containing a repeated field named value is used
*/unpackany_list=function(Gpany, deserialize, typeName) {returnGpany.unpack (Deserialize, typeName). Toobject () ["ValueList"];}; /**
* Use of any wrapped message with more than one field (message nesting also applies)
*/Unpackany_complexobject=function(Gpany, deserialize, typeName) {returnGpany.unpack (Deserialize, typeName). Toobject ();};/** * Take out the map data needed in Genericmap and unpack any type of value, assemble into a readable remap and return * @param Gpmap * @returns {{}}*/Unpackgpmap=function(gpmap) {varDataMap = gpmap[' Wrappers_ ' [' 1 '] [' MAP_ ']; varFieldList =Object.keys (DATAMAP); varReMap = {}; for(vari = 0; i < fieldlist.length; i++) {Remap[fieldlist[i]]= Unpackany (datamap[fieldlist[i]]["Valuewrapper"]); } returnReMap;}; Main ();
This article only shows the use of Google.protobuf.Any, and the concrete construction of GRPC projects in Java and Nodejs can be referenced in the following items:
Https://github.com/LogNet/grpc-spring-boot-starter
Https://github.com/grpc/grpc/tree/master/examples
Use of any type in Grpc (Java and Nodejs side)