下载示例代码 完整示例代码在 dubbo-samples 中。 下载源码 git clone -b master https://github.com/apache/dubbo-samples.git 进入示例目录 cd dubbo-samples/1-basic/dubbo-samples-spring-bootls # 查看目录结构 快速运行
下载示例代码
完整示例代码在 dubbo-samples 中。
快速运行示例
在 provider 侧会输出如下信息:
Hello World, request from consumer: xxx.xxx.xxx.xxx至此就把 Dubbo 的基本功能都实现了,可以在 Dubbo 的基础上进行更多的开发。
示例核心流程
关于示例的更详细解读可参见 注解配置
1. 定义服务接口
dubbo-samples-spring-boot-interface/DemoService.java
package org.apache.dubbo.samples.basic.api; public interface DemoService { String sayHello(String name); }2. 提供方实现接口并暴露服务
dubbo-samples-spring-boot-provider/DemoServiceImpl.java
@DubboService public class DemoServiceImpl implements DemoService { @Override public String sayHello(String name) { System.out.println("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); return "Hello " + name; } }3. 配置 application.yml 文件
dubbo-samples-spring-boot-provider/resources/application.yml
dubbo: application: name: dubbo-springboot-demo-provider protocol: name: dubbo port: -1 registry: id: zk-registry address: zookeeper://127.0.0.1:2181 config-center: address: zookeeper://127.0.0.1:2181 metadata-report: address: zookeeper://127.0.0.1:21814. 定义 Spring Boot 主函数
dubbo-samples-spring-boot-provider/ProviderApplication.java
@SpringBootApplication @EnableDubbo public class ProviderApplication { public static void main(String[] args) throws Exception { new EmbeddedZooKeeper(2181, false).start(); SpringApplication.run(ProviderApplication.class, args); System.out.println("dubbo service started"); new CountDownLatch(1).await(); } }其中,@EnableDubbo 必须配置。
5. 引用远程服务
dubbo-samples-spring-boot-consumer/ConsumerApplication.java
public class ConsumerApplication { @DubboReference private DemoService demoService; }6. 定义 application.yml
dubbo-samples-spring-boot-consumer/application.yml
dubbo: application: name: dubbo-springboot-demo-consumer protocol: name: dubbo port: -1 registry: id: zk-registry address: zookeeper://127.0.0.1:2181 config-center: address: zookeeper://127.0.0.1:2181 metadata-report: address: zookeeper://127.0.0.1:21817. 加载 Spring 配置,并调用远程服务
dubbo-samples-spring-boot-consumer/ConsumerApplication.java
@SpringBootApplication @Service @EnableDubbo public class ConsumerApplication { @DubboReference private DemoService demoService; public String doSayHello(String name) { return demoService.sayHello(name); } public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(ConsumerApplication.class, args); ConsumerApplication application = context.getBean(ConsumerApplication.class); String result = application.doSayHello("world"); System.out.println("result: " + result); } }其中,@EnableDubbo 必须配置。