概念
通常我们想调用别人的dubbo服务时,我们需要在项目中引入对应的jar包。而泛化调用的作用是,我们无需依赖相关jar包,只需要知道目标服务的名字和参数,也能调用到该服务。
这个特性一般使用在网关类项目中,在业务开发中基本不会使用。
代码地址
https://gitee.com/zjj19941/ZJJ_Dubbo.git 下的 generalization-call 项目
代码演示
consumer
package com.zjj;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class DubboConsumerDemo {
// 别的服务不提供接口给你,但是你还想用, 你就可以用泛华调用
@Reference(id = "demoService", version = "default", interfaceName = "com.zjj.DemoService", generic = true)
private GenericService genericService;
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DubboConsumerDemo.class);
//将DemoService强制转换成GenericService
GenericService genericService = (GenericService) context.getBean("demoService");
//也能调用成功
Object result = genericService.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"你好"});
System.out.println(result);
}
}
测试
首先观察zookeeper,发现已经有了com.zjj.DemoService服务了
而我的consumer并没有引入com.zjj.DemoService的Maven依赖, 通过泛化调用,也能调用到 com.zjj.DemoService ,程序执行结果我就不粘贴到这上面了,自己把代码下载下来跑一下就行了.