Dubbo的泛化调用(Generic Invocation)是指在不知道具体服务接口的情况下,通过通用的方式调用服务。泛化调用主要用于服务测试、网关等场景,可以极大地提高系统的灵活性和可扩展性。
Dubbo泛化调用的实现
Dubbo提供了GenericService
接口,用于实现泛化调用。具体步骤如下:
- 定义服务接口和实现:定义一个普通的服务接口和其实现。
- 暴露服务:通过Dubbo配置将服务暴露出去。
- 使用泛化调用:在消费者端使用
GenericService
进行服务调用。
1. 服务定义和实现
定义一个普通的服务接口DemoService
:
package com.example;
public interface DemoService {
String sayHello(String name);
}
实现服务接口,并通过Dubbo注解将其暴露为远程服务:
package com.example;
import org.apache.dubbo.config.annotation.DubboService;
@DubboService
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}
Spring Boot配置文件(application.yml):
server:
port: 8081
dubbo:
application:
name: dubbo-demo-provider
registry:
address: zookeeper://127.0.0.1:2181
protocol:
name: dubbo
port: 20880
scan:
base-packages: com.example
2. 服务消费者使用泛化调用
在消费者端,通过GenericService
进行泛化调用。
服务消费者:
package com.example;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.stereotype.Component;
@Component
public class DemoServiceConsumer {
public void execute() {
// 创建应用配置
ApplicationConfig application = new ApplicationConfig();
application.setName("dubbo-demo-consumer");
// 创建注册中心配置
RegistryConfig registry = new RegistryConfig();
registry.setAddress("zookeeper://127.0.0.1:2181");
// 创建引用配置
ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
reference.setApplication(application);
reference.setRegistry(registry);
reference.setInterface("com.example.DemoService");
reference.setGeneric("true");
// 获取引用配置缓存
ReferenceConfigCache cache = ReferenceConfigCache.getCache();
GenericService genericService = cache.get(reference);
// 泛化调用
Object result = genericService.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"World"});
System.out.println(result);
}
}
Spring Boot配置文件(application.yml):
server:
port: 8080
dubbo:
application:
name: dubbo-demo-consumer
registry:
address: zookeeper://127.0.0.1:2181
consumer:
check: false
scan:
base-packages: com.example
服务消费者启动类:
package com.example;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DubboConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(DubboConsumerApplication.class, args);
}
@Bean
public CommandLineRunner demo(DemoServiceConsumer consumer) {
return args -> consumer.execute();
}
}
运行示例
- 启动ZooKeeper。
- 启动服务提供者。
- 启动服务消费者。
在消费者的控制台中,你会看到泛化调用的结果:
Hello, World
总结
Dubbo的泛化调用通过GenericService
接口实现,使得在不知道具体服务接口的情况下也能进行服务调用。