Dubbo接口泛化调用

涉及jar包


	com.alibaba
	dubbo
	2.8.4



	com.101tec
	zkclient
	0.10

如果入参为一个对象,类似于:

Person person = new PersonImpl(); 
person.setName("xxx"); 
person.setPassword("yyy");

调用方式如下:

package com.deppon.uap.appservice.util;

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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TambcdmUtil {

    public static void main(String[] args) {

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

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

        ReferenceConfig reference = new ReferenceConfig();
        reference.setApplication(application);
        reference.setRegistry(registry);
        reference.setInterface("com.xxx.test.TestService");
        // 声明为泛化接口
        reference.setGeneric(true); 
        reference.setGroup("stestn1");
        reference.setVersion("1.0.0");
        try {
            ReferenceConfigCache cache = ReferenceConfigCache.getCache();
            GenericService genericService = cache.get(reference);

            Map maps = new HashMap();
            maps.put("name","xxx");
			maps.put("password","xxx");
            // 基本类型以及Date,List,Map等不需要转换,直接调用
            Object result = genericService.$invoke("funcName",
                    new String[]{"Person"},
                    new Object[]{maps});
            System.out.println(result);

      
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(Dubbo接口泛化调用)