W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
對 Google Protobuf 對象進行泛化調(diào)用
泛化接口調(diào)用方式主要用于客戶端沒有 API 接口及模型類元的情況,參考 泛化調(diào)用。 一般泛化調(diào)用只能用于生成的服務參數(shù)為POJO的情況,而 GoogleProtobuf 的對象是基于 Builder 生成的非正常POJO,可以通過 protobuf-json 泛化調(diào)用。
GoogleProtobuf 序列化相關的Demo可以參考 protobuf-demo
在 Spring 中配置聲明 generic = “protobuf-json”
<dubbo:reference id="barService" interface="com.foo.BarService" generic="protobuf-json" />
在 Java 代碼獲取 barService 并開始泛化調(diào)用:
GenericService barService = (GenericService) applicationContext.getBean("barService");
Object result = barService.$invoke("sayHello",new String[]{"org.apache.dubbo.protobuf.GooglePbBasic$CDubboGooglePBRequestType"}, new Object[]{"{\"double\":0.0,\"float\":0.0,\"bytesType\":\"Base64String\",\"int32\":0}"});
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
// 弱類型接口名
reference.setInterface(GenericService.class.getName());
reference.setInterface("com.xxx.XxxService");
// 聲明為Protobuf-json
reference.setGeneric(Constants.GENERIC_SERIALIZATION_PROTOBUF);
GenericService genericService = reference.get();
Map<String, Object> person = new HashMap<String, Object>();
person.put("fixed64", "0");
person.put("int64", "0");
// 參考google官方的protobuf 3 的語法,服務的每個方法中只傳輸一個POJO對象
// protobuf的泛化調(diào)用只允許傳遞一個類型為String的json對象來代表請求參數(shù)
String requestString = new Gson().toJson(person);
// 返回對象是GoolgeProtobuf響應對象的json字符串。
Object result = genericService.$invoke("sayHello", new String[] {
"com.xxx.XxxService.GooglePbBasic$CDubboGooglePBRequestType"},
new Object[] {requestString});
GoogleProtobuf 對象是由 Protocol 契約生成,相關知識請參考 ProtocolBuffers 文檔。假如有如下Protobuf 契約
syntax = "proto3";
package com.xxx.XxxService.GooglePbBasic.basic;
message CDubboGooglePBRequestType {
double double = 1;
float float = 2;
int32 int32 = 3;
bool bool = 13;
string string = 14;
bytes bytesType = 15;
}
message CDubboGooglePBResponseType {
string msg = 1;
}
service CDubboGooglePBService {
rpc sayHello (CDubboGooglePBRequestType) returns (CDubboGooglePBResponseType);
}
則對應請求按照如下方法構(gòu)造
Map<String, Object> person = new HashMap<>();
person.put("double", "1.000");
person.put("float", "1.00");
person.put("int32","1" );
person.put("bool","false" );
//String 的對象需要經(jīng)過base64編碼
person.put("string","someBaseString");
person.put("bytesType","150");
Google Protobuf 對象缺少標準的 JSON 格式,生成的服務元數(shù)據(jù)信息存在錯誤。請?zhí)砑尤缦乱蕾囋獢?shù)據(jù)解析的依賴。
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-metadata-definition-protobuf</artifactId>
<version>${dubbo.version}</version>
</dependency>
從服務元數(shù)據(jù)中也可以比較容易構(gòu)建泛化調(diào)用對象。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: