dubbo泛化调用简单示例

参考官方文档,写个简单示例
泛化引用:http://dubbo.apache.org/zh-cn/docs/user/demos/generic-reference.html
泛化实现:http://dubbo.apache.org/zh-cn/docs/user/demos/generic-service.html

package com.dubbodemo;

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 com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;

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

/**
 *  * @author guoxi.li
 *  * @Description:
 */
public class DubboConsumerGenericService {
    private static final Logger logger = Logger.getLogger(DubboConsumerGenericService.class);

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

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

        ReferenceConfig reference = new ReferenceConfig();
        reference.setApplication(application);
        reference.setRegistry(registry);
        reference.setVersion("0.0.1_IMC");
        reference.setInterface("com.dubbodemo.biz.MyBiz");
        reference.setGeneric(true); // 声明为泛化接口

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

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

        String result = JSON.toJSONString(resultObj);
        logger.info("-------------->>>result:"+ result);
        return result;
    }

    public static void main(String[] args) {
        int invokeConut = 1; //此处设置调用次数
        String result = "";
        for (int i=0; i>>result:"+ 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;
                }
            }
        }
    }

}

注意:版本号、注册中心地址和接口服务名一定要有。

你可能感兴趣的:(微服务框架)