本文使用的springboot版本为2.0.6.RELEASE
dubbo-spring-boot-starter使用阿里巴巴提供的,版本为0.2.0,依赖dubbo版本为2.6.2
0.2.1+版本依赖的springboot版本为2.1.x
如果想使用2.7.0+版本的dubbo可以使用apache提供的dubbo-spring-boot-starter
springboot版本也需要依赖到2.1.x
下面有项目链接作为参考
创建服务接口工程
- 创建一个User类
public class User implements Serializable {
private static final long serialVersionUID = -1563308959112481804L;
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
- 创建服务接口
public interface TestService {
String getString(String src);
User getUser(String name, int age);
}
服务接口工程只提供接口不提供实现。
创建完了需要maven install,在后续的消费和生产中使用
创建生产者,提供服务
- 引入依赖
demo.springboot
dubbo-service
1.0-SNAPSHOT
com.alibaba.boot
dubbo-spring-boot-starter
0.2.0
org.springframework.boot
spring-boot-starter
- 修改配置文件
application:
#版本号
version: 1.0.0
dubbo:
application:
#应用名称,每个dubbo应用的名称都是唯一的
name: dubbo-producer
registry:
#注册中心
address: zookeeper://172.16.77.131:2181
protocol:
#协议名称
name: dubbo
#服务暴露端口
port: 20880
scan:
#扫描服务注册bean,即service实现类所在的包
basePackages: demo.springboot.service.impl
- 实现服务接口
//此处的@Service是dubbo提供的,不是spring中的
@Service(version = "${application.version}")
public class TestServiceImpl implements TestService {
@Override
public String getString(String src) {
return src;
}
@Override
public User getUser(String name, int age) {
User user = new User();
user.setName(name);
user.setAge(age);
return user;
}
}
- 创建启动类
@SpringBootApplication
public class ProducerApplication {
public static void main(String[] args) {
//生产者不需要是web项目
new SpringApplicationBuilder(ProducerApplication.class)
.web(WebApplicationType.NONE) //非web应用
.run(args);
}
}
运行springboot启动类,启动服务
创建消费者,消费服务
- 引入依赖
demo.springboot
dubbo-service
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-web
com.alibaba.boot
dubbo-spring-boot-starter
0.2.0
- 修改配置文件
server:
port: 8080
servlet:
context-path: /
application:
#版本号
version: 1.0.0
dubbo:
application:
#应用名称,每个dubbo应用的名称都是唯一的
name: dubbo-consumer
registry:
#注册中心
address: zookeeper://172.16.77.131:2181
- 创建controller
@RestController
public class TestController {
//使用dubbo提供的@Reference装配bean
@Reference(version = "${application.version}")
private TestService testService;
@GetMapping("/getString")
public String getString(String src){
return testService.getString(src);
}
@GetMapping("/getUser")
public User getUser(String name, Integer age){
return testService.getUser(name, age);
}
}
- 创建启动类
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
启动消费者项目,浏览器访问对应的请求就可以了。
项目路径
作者博客
作者公众号
