最近在学习dubbo,构建一个简单的springboot集成dubbo,中间也是出了好多问题,在这记录下整体的过程。
1. 构建SpringBoot环境
一个简单的聚合工程
- dubbo-consumer:是服务消费方
- dubbo-provider:是服务提供方
- dubbo-interface:存放接口,因为dubbo是根据接口进行服务注册发现的,因此我们要把接口单独拿出来,provider提供方实现该接口并注册服务, consumer要根据接口进行注入
完整demo路径
2.dubbo-provider服务配置
2.1 引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>3.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-dependencies-zookeeper</artifactId>
<version>3.0.7</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>dubbo-service</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>dubbo-service</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
2.2 application.yml 配置
server:
port: 8081
dubbo:
protocol:
name: dubbo
port: 20880
registry:
address: zookeeper://127.0.0.1:2181
application:
name: provider
2.3 配置启动类
@SpringBootApplication
@EnableDubbo
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
这里注意@EnableDubbo
2.4 编写实现类
可以先实现下面的接口,回过头来写实现类
@DubboService
public class DemoServiceImpl implements DemoService {
@Override
public String getUsername(String name) {
return "dubbo3新技术欢迎你 ! "+name;
}
}
这里注意@DubboService
因为这个注解缺失,demo一直报错
3.dubbo-service配置
3.1 编写接口
public interface DemoService {
public String getUsername(String name);
}
4.dubbo-consumer配置
4.1 引入依赖
同上面的2.1
复制就好了
4.2 application.yml 配置
server:
port: 8082
dubbo:
registry:
address: zookeeper://127.0.0.1:2181
application:
name: consumer
4.3 配置启动类
@SpringBootApplication
@EnableDubbo
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
}
4.4 编写个接口,用来测试
@RestController
public class DemoController {
@DubboReference
private DemoService demoService;
@GetMapping("/get/{username}")
public String getUsername(@PathVariable String username) {
return demoService.getUsername(username);
}
}
注意这里的@DubboReference
5.测试
依此启动Zookeeper
-> provider
-> consumer
至此一个简单地springboot + dubbo + zookeeper
的demo就实现了,本来不打算写博客的,构建时中间一直出错,网上相关资料也不多,索性记录一下,后续有时间会用dubbo
构建一个完整项目