Dubbo3 GoogleProtobuf 對象泛化調(diào)用

2022-03-31 11:09 更新

對 Google Protobuf 對象進行泛化調(diào)用

泛化接口調(diào)用方式主要用于客戶端沒有 API 接口及模型類元的情況,參考 泛化調(diào)用。 一般泛化調(diào)用只能用于生成的服務(wù)參數(shù)為POJO的情況,而 GoogleProtobuf 的對象是基于 Builder 生成的非正常POJO,可以通過 protobuf-json 泛化調(diào)用。

GoogleProtobuf 序列化相關(guān)的Demo可以參考 protobuf-demo

通過Spring對Google Protobuf對象泛化調(diào)用

在 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}"});

通過 API 方式對 Google Protobuf 對象泛化調(diào)用

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 的語法,服務(wù)的每個方法中只傳輸一個POJO對象
// protobuf的泛化調(diào)用只允許傳遞一個類型為String的json對象來代表請求參數(shù)
String requestString = new Gson().toJson(person);
// 返回對象是GoolgeProtobuf響應(yīng)對象的json字符串。
Object result = genericService.$invoke("sayHello", new String[] {
    "com.xxx.XxxService.GooglePbBasic$CDubboGooglePBRequestType"},
    new Object[] {requestString});

GoogleProtobuf 對象的處理

GoogleProtobuf 對象是由 Protocol 契約生成,相關(guān)知識請參考 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);
}

則對應(yīng)請求按照如下方法構(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");

GoogleProtobuf 服務(wù)元數(shù)據(jù)解析

Google Protobuf 對象缺少標(biāo)準(zhǔn)的 JSON 格式,生成的服務(wù)元數(shù)據(jù)信息存在錯誤。請?zhí)砑尤缦乱蕾囋獢?shù)據(jù)解析的依賴。

<dependency>
    <groupId>org.apache.dubbo</groupId>
    <artifactId>dubbo-metadata-definition-protobuf</artifactId>
    <version>${dubbo.version}</version>
</dependency>

從服務(wù)元數(shù)據(jù)中也可以比較容易構(gòu)建泛化調(diào)用對象。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號