Dubbo服务接口
dubbo服务接口定义在第二方或第三方jar包中,服务提供方和消费方都需要引用
public interface PrintService {
String print(String src);
}
Dubbo服务提供方
1. 引入依赖
<dependencies>
<!-- Dubbo 服务接口 -->
<dependency>
<groupId>cloud.alibaba.example</groupId>
<artifactId>dubbo-sample-api</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Nacos服务注册与发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- dubbo依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
</dependencies>
2. 实现服务接口
@DubboService // 暴露服务
public class PrintServiceImpl implements PrintService {
@Override
public String print(String src) {
return "print:" + src;
}
}
3. application.yml
dubbo:
scan:
# Dubbo 扫描服务接口实现类的包
base-packages: cloud.alibaba.example.service.impl
protocol:
# Dubbo 协议
name: dubbo
# Dubbo 协议暴露的端口(-1表示自增,默认从20880自增)
port: -1
registry:
# 挂载到Spring Cloud注册中心
address: spring-cloud://localhost
spring:
application:
# Dubbo 服务名称
name: dubbo-provider
main:
# Spring Boot 2.1 需要设定
allow-bean-definition-overriding: true
cloud:
# Nacos 服务注册与发现
nacos:
discovery:
server-addr: localhost:8848
4. 启动类
@EnableDiscoveryClient
@EnableAutoConfiguration //如果只使用dubbo的bean,则不需要使用@SpringBootApplication
public class DubboProviderApplication {
public static void main(String[] args) {
// 非web项目启动
new SpringApplicationBuilder(DubboProviderApplication.class)
.web(WebApplicationType.NONE)
.run(args);
}
}
DubboProviderApplication启动后Nacos中就会出现dubbo-provider服务
Dubbo服务消费方
1. 引入依赖
<dependencies>
<!-- Dubbo 服务接口 -->
<dependency>
<groupId>cloud.alibaba.example</groupId>
<artifactId>dubbo-sample-api</artifactId>
<version>${project.version}</version>
</dependency>
<!-- web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Nacos服务注册与发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- dubbo依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
</dependencies>
2. application.yml
server:
port: 8030
dubbo:
protocol:
name: dubbo
port: -1
cloud:
# 订阅服务提供方应用列表,多个应用订阅以,隔开。默认*订阅所有应用
subscribed-services: dubbo-provider
registry:
address: spring-cloud://localhost
spring:
application:
name: dubbo-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
3. 启动类
@EnableDiscoveryClient
@EnableAutoConfiguration
@RestController
public class DubboConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(DubboConsumerApplication.class, args);
}
@DubboReference // 引用dubbo服务
private PrintService printService;
@GetMapping("print")
public String print(String src){
return printService.print(src);
}
}
4. 测试
访问服务消费方的接口
curl http://localhost:8030/print?src=hello
print:hello