注意:本篇文章主要是测试dubbo下的业务,并非测试dubbo框架本身
在如下情况下可以使用这种方式
- dubbo消费端不到服务端提供API或者jar包
- 想通过http接口测试dubbo
- 字符串和对象的互相转化
核心伪代码,利用下面的代码起一个HTTP服务
class DubboParams {
public String url;
public String method;
public String params;
public String interfaceName;
public String type;
public String value;
public String getType() {
return type;
}
public DubboParams setType(String type) {
this.type = type;
return this;
}
public String getValue() {
return value;
}
public DubboParams setValue(String value) {
this.value = value;
return this;
}
public String getUrl() {
return url;
}
public DubboParams setUrl(String url) {
this.url = url;
return this;
}
public String getMethod() {
return method;
}
public DubboParams setMethod(String method) {
this.method = method;
return this;
}
public String getParams() {
return params;
}
public DubboParams setParams(String params) {
this.params = params;
return this;
}
public String getInterfaceName() {
return interfaceName;
}
public DubboParams setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
return this;
}
}
public Response runDubbo( DubboParams dubboParams){
String url = dubboParams.getUrl();
String method = dubboParams.getMethod();
String interfaceName = dubboParams.getInterfaceName() ;
String types = dubboParams.getType();
String values = dubboParams.getValue();
JSONArray jsonArray = JSON.parseArray(types);
String[] parameterTypes = new String[jsonArray.size()];
for(int i=0;i<jsonArray.size();i++ ){
// 设置参数类型
parameterTypes[i] = jsonArray.get(i).toString();
}
JSONArray jsonArray1 = JSON.parseArray(values);
Object[] parameterObjs = new Object[jsonArray1.size()];
jsonArray1.toArray(parameterObjs);
// Application Info
ApplicationConfig application = new ApplicationConfig();
application.setName("yyy");
// Registry Info
RegistryConfig registry = new RegistryConfig();
// 无注册中心
registry.setAddress("N/A");
// NOTES: ReferenceConfig holds the connections to registry and providers, please cache it for performance.
// Refer remote service
ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>(); // In case of memory leak, please cache.
reference.setApplication(application);
reference.setRegistry(registry);
// 直连url
reference.setUrl(url);
reference.setInterface(interfaceName);
reference.setGeneric(true);
// Use xxxService just like a local bean
// 客户端泛泛调用
GenericService genericService = reference.get();
Object result = genericService.$invoke(method, parameterTypes, parameterObjs);
System.out.println(result.toString());
return Response.ok().putData(result);
}
利用postman调用http接口,从而实现调用dubbo接口