Dubbo入门学习二:Dubbo的泛化调用

泛化接口调用方式主要用于客户端没有API 接口及模型类元的情况,参数及返回值中的所有 POJO均用 Map 表示,通常用于框架集成,比如:实现一个通用的服务测试框架,可通过 GenericService调用所有服务实现。

服务提供者

1.Spring配置文件




    
    

    
    

    
    

    
    

    
    


2.服务提供类

package com.alibaba.dubbo.demo.provider;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Provider {
    public static void main(String[] args) throws Exception {
        System.setProperty("java.net.preferIPv4Stack", "true");
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-provider.xml"});
        context.start();
        System.in.read(); // press any key to exit
    }
}

服务调用者—API调用方式

泛化实现类-GenericConsumer

package com.alibaba.dubbo.demo.consumer;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.rpc.service.GenericService;

public class GenericConsumer {
    public static void main(String[] args) {
        ReferenceConfig reference = new ReferenceConfig();
        // 弱类型接口名
        reference.setInterface("com.alibaba.dubbo.demo.DemoService");
        reference.setVersion("1.0.0");
        // 声明为泛化接口
        reference.setGeneric(true);

        //应用名称
        ApplicationConfig application = new ApplicationConfig("demo-consumer");
        reference.setApplication(application);

        //初始化dubbo注册中心配置
        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol("zookeeper");
        registry.setAddress("127.0.0.1:2181");
        reference.setRegistry(registry);
        // 用com.alibaba.dubbo.rpc.service.GenericService可以替代所有接口引用
        GenericService genericService = reference.get();

        // 基本类型以及Date,List,Map等不需要转换,直接调用
        Object result = genericService.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"nezha-world"});
        System.out.println("================="+result);
    }
}

服务调用者—Spring配置方式

1.dubbo-demo-generic-consumer.xml

配置文件路径:resources目录下--->>>``META-INF/spring/dubbo-demo-generic-consumer.xml




    
    

    
    

    
    

2.GenericConsumer

package com.alibaba.dubbo.demo.consumer;

import com.alibaba.dubbo.rpc.service.GenericService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class GenericConsumer {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-generic-consumer.xml"});
        context.start();
        GenericService genericService = (GenericService) context.getBean("demoService");
        Object result = genericService.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"nezha-world"});
        System.out.println("================="+result);
    }
}

参考文献

1.Dubbo官方使用手册—泛化的使用

你可能感兴趣的:(Dubbo入门学习二:Dubbo的泛化调用)