首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Dubbo接口泛化调用

Dubbo接口泛化调用

作者头像
软件测试君
发布于 2019-12-19 16:32:52
发布于 2019-12-19 16:32:52
1.7K0
举报
文章被收录于专栏:测试人生测试人生
涉及jar包:
代码语言:javascript
复制
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>dubbo</artifactId>
    <version>2.8.4</version>
</dependency>
<dependency>
    <groupId>com.101tec</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.10</version>
</dependency>
如果入参为一个对象,类似于:
代码语言:javascript
复制
Person person = new PersonImpl(); 
person.setName("xxx"); 
person.setPassword("yyy");
调用方式如下:
代码语言:javascript
复制
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<GenericService> reference = new ReferenceConfig<GenericService>();
        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<String, Object> maps = new HashMap<String, Object>();
            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();
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-12-11,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 如果入参为一个对象,类似于:
  • 调用方式如下:
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档