1.启动zookeeper服务
首先使用命令行窗口进入到zookeeper,使用zkServer.cmd命令启动zookeeper服务。

2.启动dubbon服务
我们将之前打好的war包放到Tomcat的webapps文件下,启动tomcat访问http://127.0.0.1:8081/dubbo-admin-2.8.4/链接进入dubbon-admin控制台。然后登录用户名和密码进入控制台。

3.开启2个SpringBoot服务
首先我们先创建一个SpringBoot服务命名为provider作为服务提供者。
依赖(provider,consumer的pom文件都加上dubbon,zk依赖)
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
然后配置服务提供者的配置文件
dubbo.application.name=provider
dubbo.registry.address=127.0.0.1:2181
dubbo.registry.protocol=zookeeper
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
dubbo.monitor.protocol=registry
java代码
public interface UserService {
public String getMsg();
}
注意@Service注解为import com.alibaba.dubbo.config.annotation.Service
这个包下的注解
@Service
@Component
public class UserServiceImpl implements UserService{
@Override
public String getMsg() {
return "{\"userName\":\"admin\",\"userId\":1,\"userPwd\":\"admin\"}";
}
}
最后在SpringBoot的启动类上加@EnableDubbo 代表开启基于注解的bubbo功能
@EnableDubbo
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
启动服务提供者再dubbon中可以看到如图3所示,代表服务注册成功。

接着我们启动另一个SpringBoot服务,consumer服务消费者。
<dependency>
<groupId>com.alibaba.spring.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
</dependency>
配置文件
server.port=8089
dubbo.application.name=consumer
dubbo.registry.address=zookeeper://127.0.0.1:2181
dubbo.monitor.protocol=registry
首先编写一个UserService 借口不写实现类。
public interface UserService {
public String getMsg();
}
在DubboService 类中getMsg方法中调用服务提供者的getMsg方法。
@Service
public class DubboService {
@Reference
UserService userService;
public String getMsg(){
String msg = userService.getMsg();
return msg;
}
}
@Controller
@RequestMapping("/test")
public class TestController {
@Autowired
private DubboService dubboService;
@ResponseBody
@RequestMapping("/dubbon")
public String getMsg(){
return dubboService.getMsg();
}
}
@EnableDubbo
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
启动服务者服务如图4所示代表服务消费者启动消费正常。

最后我们在浏览器输入http://127.0.0.1:8089/test/dubbon出现图5所示,代表服务消费者已消费服务提供者提供的服务。

总结:使用SpringBoot整合Dubbon主要分为4部,第一步导入依赖,第二步配置applicatiion文件,第三步,使用@Service(暴露服务)@reference(引用服务)第四步在启动类上配置@EnableDubbo 注解。
网友评论