1.导入依赖
<dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>2.12.0</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>2.12.0</version> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.14</version> <!--排除这个slf4j-log4j12--> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> <version>0.1</version> </dependency>
2.在服务提供者模块配置文件配置注册中心
dubbo.application.name=provider dubbo.registry.address=zookeeper://xxxxx:2181 dubbo.scan.base-packages=com.ws.service server.port=8001
3.编写服务提供者服务(注意@Service是dubbo里的)
package com.ws.service; import org.apache.dubbo.config.annotation.Service; import org.springframework.stereotype.Component; @Component @Service //dubbo里的service public class TicketServiceImpl implements TickerService{ @Override public String getTicket() { return "恭喜拿到票"; } }
4.在消费者配置文件里配置服务取出地址
server.port=8002 dubbo.application.name=consumer dubbo.registry.address=zookeeper://39.105.66.142:2181
5.编写消费者(此处的远程调用需要在消费者服务同一级目录下有着和提供者一样的接口或在pom文件里引入提供者)
package com.ws.service; import org.apache.dubbo.config.annotation.Reference; import org.springframework.stereotype.Service; @Service public class UserService { @Reference //远程调用 TickerService tickerService; public void buyTicker(){ System.out.println(tickerService.getTicket()); } }
5.调用UserService里的buyTicket方法进行测试