How do consumers in Dubbo invoke providers.
To invoke the Dubbo provider, consumers need to follow these steps:
- Introducing Dubbo dependency: In the consumer’s project, add Dubbo’s dependency by using Maven or Gradle.
- Configure the Dubbo settings for consumers: In the consumer’s configuration file, specify the Dubbo registry address, consumer’s application name, protocol, etc.
- Introducing service interface: in the consumer project, include the interface of the service provider, which can be done by either dependency or manual inclusion.
- To invoke a service in code: create a proxy object and call the service provider’s interface method to access the service.
The example code is shown below:
// 引入服务接口
import com.example.service.UserService;
// 在代码中调用服务
public class Consumer {
public static void main(String[] args) {
// 配置Dubbo
ApplicationConfig application = new ApplicationConfig();
application.setName("consumer");
RegistryConfig registry = new RegistryConfig();
registry.setAddress("zookeeper://localhost:2181");
ReferenceConfig<UserService> reference = new ReferenceConfig<>();
reference.setApplication(application);
reference.setRegistry(registry);
reference.setInterface(UserService.class);
// 获取服务代理对象
UserService userService = reference.get();
// 调用服务提供者的方法
String result = userService.getUserInfo("123");
System.out.println(result);
}
}
In the above example, it is necessary to configure the relevant information of Dubbo based on the actual situation, such as the address of the registration center and the interface. Afterwards, create a proxy object for the service using ReferenceConfig, and use this proxy object to call methods of the service provider.