dubbo泛化:
以下几种场景可以考虑使用泛化调用:
服务测试平台
API 服务网关
泛化调用主要用于消费端没有 API 接口的情况;不需要引入接口 jar 包,而是直接通过 GenericService 接口来发起服务调用,参数及返回值中的所有 POJO 均用 Map 表示。泛化调用对于服务端无需关注,按正常服务进行暴露即可。
官方文档链接:http://dubbo.apache.org/zh-cn/blog/dubbo-generic-invoke.html
dubbo泛化示例:
package dubbo;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.service.GenericService;
public class DubboGeneric {
/**
* 执行dubbo方法
*
* @param method dubbo方法
* @param paramTypes 入参类型数组
* @param params 入参
* @return 执行方法的结果
*/
static void executMethod(String method, String[] paramTypes, String[] params) {
String zookeeperUrl = "127.0.0.1:2881";
String providerUrl = "127.0.0.1:1234";
String interfaceName = "com.mine.dubbo.demo.DemoService";
String interfaceVerison = "";
String group = "";
// 获取泛化对象
GenericService genericService = getGenericService(zookeeperUrl, providerUrl, interfaceName, interfaceVerison, group);
// for(String method: method){
// 泛化调用
genericService.$invoke(method, paramTypes, params);
// }
}
/**
* 获取泛化对象
* @param zookeeperUrl zookeeper集群地址
* @param providerUrl 服务提供者的地址
* @param interfaceName 接口文件全路径名
* @param interfaceVerison 接口版本
* @param group 组名
* @return 泛化对象
*/
static GenericService getGenericService(String zookeeperUrl, String providerUrl, String interfaceName,
String interfaceVerison, String group) {
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>();
// set application
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("");
applicationConfig.setOwner("");
applicationConfig.setOrganization("");
reference.setApplication(applicationConfig);
// set zookeeper or provider
if (zookeeperUrl != null && zookeeperUrl.trim().length() != 0) {
// 通过zookeeper连接
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress(zookeeperUrl);
registryConfig.setProtocol("zookeeper");
registryConfig.setCheck(false);
reference.setRegistry(registryConfig);
} else {
// 直连
reference.setUrl(providerUrl);
}
// set timeout
reference.setTimeout(1000);
// set retry times
reference.setRetries(0);
// set check
reference.setCheck(false);
// set generic
reference.setGeneric(true);
// set interface version
if (interfaceVerison != null && interfaceVerison.length() != 0) {
reference.setVersion(interfaceVerison);
}
// set interface name
reference.setInterface(interfaceName);
// set service id
reference.setId(interfaceName);
// set dubbo protocol
reference.setProtocol("dubbo");
//
if (group != null && group.length() != 0) {
reference.setGroup(group);
}
// 从zookeeper获取缓存,从缓存中获取泛化
GenericService genericService = ReferenceConfigCache.getCache().get(reference);
return genericService;
}
}