dubbo 泛化调用简单小例子

参考官方文档,写了个小例子。

dubbo 泛化引用:http://dubbo.io/books/dubbo-user-book/demos/generic-reference.html

dubbo 泛化实现:http://dubbo.io/books/dubbo-user-book/demos/generic-service.html

import com.demo.common.util.JsonUtil;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.rpc.service.GenericService;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author changle
 *         time 18/3/7.
 *         dubbo 泛化调用示例
 */
public class DubboConsumerGenericService {
    public static void main(String[] args) {

        // 普通编码配置方式
        ApplicationConfig application = new ApplicationConfig();
        application.setName("generic-consumer");

        // 连接注册中心配置
        RegistryConfig registry = new RegistryConfig();
        registry.setAddress("zookeeper://196.168.21.89:2181");

        ReferenceConfig reference = new ReferenceConfig();
        reference.setApplication(application);
        reference.setRegistry(registry);
        reference.setVersion("1.0.0");
        reference.setInterface("com.demo.rpc.service.OppenService");
        reference.setGeneric(true); // 声明为泛化接口

        ReferenceConfigCache cache = ReferenceConfigCache.getCache();
        GenericService genericService = cache.get(reference);

        // 基本类型以及Date,List,Map等不需要转换,直接调用
        Object result = genericService.$invoke("getUserInfo", new String[] { "java.lang.Long", "java.lang.String"},
                new Object[] {2, "100123"});
        removeClassFeild(result);

        System.out.println(JsonUtil.getJsonStr(result));
    }
    private static void removeClassFeild(Object object){
        if (object instanceof Map){
            Map feildValueMap = (Map) object;
            if (feildValueMap.containsKey("Class")||feildValueMap.containsKey("class")){
                feildValueMap.remove("Class");
                feildValueMap.remove("class");
            }
            Set set = feildValueMap.entrySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()){
                Map.Entry entry = iterator.next();
                Object value = entry.getValue();
                if (value instanceof Map){
                    removeClassFeild(value);
                }else{
                    return;
                }
            }
        }
    }

}

注意版本号和接口服务名一定要有。

你可能感兴趣的:(dubbo)