概念

通常我们想调用别人的dubbo服务时,我们需要在项目中引入对应的jar包。而泛化调用的作用是,我们无需依赖相关jar包,只需要知道目标服务的名字和参数,也能调用到该服务。
这个特性一般使用在网关类项目中,在业务开发中基本不会使用。

代码地址

https://gitee.com/zjj19941/ZJJ_Dubbo.git 下的 generalization-call 项目

代码演示

consumer

  1. package com.zjj;
  2. import org.apache.dubbo.config.annotation.Reference;
  3. import org.apache.dubbo.rpc.service.GenericService;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.context.ConfigurableApplicationContext;
  7. @SpringBootApplication
  8. public class DubboConsumerDemo {
  9. // 别的服务不提供接口给你,但是你还想用, 你就可以用泛华调用
  10. @Reference(id = "demoService", version = "default", interfaceName = "com.zjj.DemoService", generic = true)
  11. private GenericService genericService;
  12. public static void main(String[] args) {
  13. ConfigurableApplicationContext context = SpringApplication.run(DubboConsumerDemo.class);
  14. //将DemoService强制转换成GenericService
  15. GenericService genericService = (GenericService) context.getBean("demoService");
  16. //也能调用成功
  17. Object result = genericService.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"你好"});
  18. System.out.println(result);
  19. }
  20. }

测试

首先观察zookeeper,发现已经有了com.zjj.DemoService服务了
image.png
而我的consumer并没有引入com.zjj.DemoService的Maven依赖, 通过泛化调用,也能调用到 com.zjj.DemoService ,程序执行结果我就不粘贴到这上面了,自己把代码下载下来跑一下就行了.