Nacos学习笔记(二)
一、SpringBoot + Nacos + Dubbo
1、工程结构
- api目录:存放消费者与提供者调用的service接口
- consumer目录:消费者目录 调用提供者远程提供的接口实现
- provider目录:提供者目录 提供给消费者接口实现
2、引入依赖
父模块:
<!-- nacos & dubbo -->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo-registry-nacos</artifactId>
<version>2.6.7</version>
</dependency>
注意:版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。
cosumer和provider模块引入api模块:
<!-- api -->
<dependency>
<groupId>com.zilong</groupId>
<artifactId>api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
2、yml配置
provider:
server:
port: 8061
dubbo:
scan:
basePackages: com.zilong.provider.service
application:
name: dubbo-provider
registry:
address: nacos://127.0.0.1:8848
protocol: nacos
check: false
protocol:
name: dubbo
port: 30003
monitor:
protocol: register
consumer:
check: false
timeout: 3000
consumer:
server:
port: 8082
dubbo:
scan:
basePackages: com.zilong.comsumer.service
application:
name: dubbo-consumer
registry:
address: nacos://127.0.0.1:8848
protocol: nacos
check: false
monitor:
protocol: register
consumer:
check: false
timeout: 3000
3、api模块接口
package com.zilong.api.service;
public interface CostService {
/**
* 消费接口
* @return
*/
Integer cost();
}
4、consumer模块
// 注解开启dubbo
@EnableDubbo
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
/**
* 购物 controller
*/
@RestController
public class ShoppingController {
@Resource
private ShoppingService shoppingService;
/**
* go shopping ~
* @return
*/
@RequestMapping("/shopping")
public String shopping(){
return shoppingService.shopping();
}
}
// 使用spring的注解 org.springframework.stereotype.Service
@Service
public class ShoppingServiceImpl implements ShoppingService {
/**
* 使用dubbo的注解 com.alibaba.dubbo.config.annotation.Reference。进行远程调用service
*/
@Reference
private CostService costService;
@Override
public String shopping() {
return "逛街......消费:" + costService.cost() + "......逛完街,回家睡觉。";
}
}
5、provider模块
// 使用dubbo的注解 com.alibaba.dubbo.config.annotation.Service
@Service
public class CostServiceImpl implements CostService {
/**
* cost TAT
* @return
*/
@Override
public Integer cost() {
return 9999;
}
}
6、验证