简介
官方文档:
实践
服务端:
-
定义服务端接口
public interface LotteryDrawApi{ RpcResult<String> draw(DrawReq req); }
-
服务端接口实现
- 引入dubbo-spring-boot-starter依赖
<dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>3.1.11</version> </dependency>
- 引入注册中心zookeeper依赖
<dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-registry-zookeeper</artifactId> <version>3.1.11</version> </dependency>
- 实现接口。
- 使用@DubboService注解标志这是个dubbo服务
@DubboService public class LotteryDrawApiImpl implements LotteryDrawApi { public LotteryDrawApiImpl() { System.out.println("====> dubbo服务端启动成功"); } @Override public RpcResult<String> draw(DrawReq req) { System.out.println("生产者调用成功!"); return RpcResult.success("抽奖成功,中500万!!!"); } }
- 添加spring-dubbo配置
- 参数:
- scan:指定dubbo服务接口包(spring会去处理该包下带Dubbo标签的类)
- protocol.port:指定dubbo服务网络端口
- registry:注册中心配置,这里使用的zookeeper,具体zookeeper使用见下一篇章
dubbo: scan: base-packages: com.daiyi.lottery.application application: name: dubbo-springboot-demo-provider protocol: name: dubbo port: 30888 registry: address: zookeeper://zookeeper-server.com:2181 timeout: 5000
- 参数:
- 引入dubbo-spring-boot-starter依赖
-
启动springboot服务
启动服务端成功!
客户端:
-
引入dubbo服务端服务
<dependency> <groupId>com.daiyi</groupId> <artifactId>lottery-rpc</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
-
和服务端一样引入dubbo框架和注册中心框架
<dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>3.1.11</version> </dependency> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-registry-zookeeper</artifactId> <version>3.1.11</version> </dependency>
-
添加spring-dubbo配置
dubbo: scan: base-packages: com.daiyi.lottery.application application: name: dubbo-springboot-demo-consumer protocol: name: dubbo port: 30889 registry: address: zookeeper://zookeeper-server.com:2181 timeout: 5000
-
编写客户端进行调用
- @DubboReference注解表示引用一个dubbo服务
@Service public class DubboClient { @DubboReference private LotteryDrawApi lotteryDrawApi; public void draw(){ System.out.println(lotteryDrawApi.draw(null).getEntity()); } }
-
启动客户端进行调用
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class); DubboClient dubboClient = context.getBean(DubboClient.class); dubboClient.draw(); } }
调用成功 ====>