创建一个dubbo微服务项目
首先创建一个父项目,vhukze-dubbo-parent-pom,依赖引入,打包类型是pom
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>0.2.0</version> </dependency>
在此项目下创建子项目,接口父项目,vhukze-dubbo-public-api-service,打包方式是pom
在接口父项目下创建子项目,服务提供者的接口项目,vhukze-dubbo-public-api-member-service,打包方式是pom,写一个接口,
package com.vhukze.api.member; public interface IMemberService { String getUser(); }
在parent父项目下创建上面服务提供者接口项目的实现项目,vhukze-dubbo-api-member-service-impl,打包方式jar,引入要实现的接口项目依赖
<dependency> <artifactId>vhukze-dubbo-public-api-member-service</artifactId> <groupId>com.vhukze</groupId> <version>1.0-SNAPSHOT</version> </dependency>
写一个类实现接口,下面的Service注解是Dubbo里面的注解
package com.vhukze.api.member.impl; import com.alibaba.dubbo.config.annotation.Service; import com.vhukze.api.member.IMemberService; @Service public class MemberServiceImpl implements IMemberService { @Override public String getUser() { return "订单服务调用会员服务"; } }
写一个启动类
package com.vhukze; import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Hello world! * */ @SpringBootApplication //开启dubbo服务,自动扫描Service注解的类,可以不在配置文件中添加扫包配置 @EnableDubbo public class App { public static void main( String[] args ) { SpringApplication.run(App.class); } }
resources下application.yml配置文件
##服务器端口号 server: port: 8080 ##注册到注册中心的名字 dubbo: application: name: member #采用协议的方式 protocol: name: dubbo #发布dubbo端口号 port: 20880 #注册中心地址 registry: address: zookeeper://127.0.0.1:2181 scan: #实现类扫包范围 base-packages: com.vhukze.api.member.impl
服务提供者写好了
创建服务消费者项目,在parent父项目下,vhuzke-dubbo-order-web,打包方式jar
resources下application配置文件
server: port: 8081 ###dubbo 注册服务名称 dubbo: application: name: order # ###dubbo服务地址 # protocol: # name: dubbo # port: 20880 registry: address: zookeeper://localhost:2181 consumer: timeout: 5000
写一个controller用来测试访问,Reference注解是从dubbo中注入实例,Service注解添加进来的实例。
这里直接注入实例到注解就行
package com.vhukze.controller; import com.alibaba.dubbo.config.annotation.Reference; import com.vhukze.api.member.IMemberService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController class OrderController { @Reference private IMemberService iMemberService; @RequestMapping("/orderToMember") public String OrderToMember(){ return iMemberService.getUser(); } }
启动zookeeper,访问上面的controller中的接口
http://localhost:8081/orderToMember