前言
搭建一个SpringBoot+Dubbo+Nacos的demo,以Dubbo作为远程调用协议,以Nacos作为Dubbo服务的注册中心和配置中心
一、环境准备
| JDK | Nacos | SpringBoot | Dubbo |
|---|---|---|---|
| jdk-8u211 | 2.2.5.RELEASE | 2.3.6.RELEASE | 2.7.7 |
1.Nacos配置单节点启动
1.1 start.cmd配置文件修改
1.2 命令行单节点启动
startup.cmd -m standalone
1.3 Nacos持久化配置
二、项目结构
项目使用Maven构建,使用IntelliJ IDEA 2022.1.4开发,并没有使用Consumer和Provider形式去搭建,而是在SpringCloud环境下搭建的微服务模式,只是为测试Nacos注册中心的功能
Maven依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-spring-boot-starter</artifactId>
<version>2.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo-registry-nacos</artifactId>
<version>2.7.7</version>
</dependency>
bootstrap.yml
server:
port: 8085
nacos:
service-address: 127.0.0.1
port: 8848
spring:
profiles:
active: dev
application:
name: spring-nacos
cloud:
nacos:
discovery:
server-addr: ${nacos.service-address}:${nacos.port}
config:
server-addr: ${nacos.service-address}:${nacos.port}
file-extension: yaml
group: DEV_GROUP
namespace: 4485c917-2a40-41ed-81b1-8e6ae2a56e4c
prefix: ${spring.profiles.active}
refresh-enabled: true
Nacos配置dev.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT
username: root
password: root
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.zhangjiang.mapper
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
dubbo:
application:
name: spring-nacos
protocol:
name: dubbo
port: 20880
registry:
id: nacos-registry
address: nacos://127.0.0.1:8848
config-center:
address: nacos://127.0.0.1:8848
metadata-report:
address: nacos://127.0.0.1:8848
三、接口代码实现
项目主启动类
Dubbo2.7.7版本提供了@EnableDubbo注解来用于和Spring的整合,而真正起作用的是@EnableDubboConfig和@DubboComponentScan这两个注解,主要作用是初始化Dubbo核心组件,加载Dubbo配置到内存中;注册BeanPostProccessor,用来扫描@DubboService注解(2.7.7之后的)
@SpringBootApplication
@EnableDiscoveryClient
@EnableDubbo(scanBasePackages = "com.zhangjiang.service")
@MapperScan(basePackages = "com.zhangjiang.mapper")
public class SpringNacosApplication {
public static void main(String[] args) {
SpringApplication.run(SpringNacosApplication.class, args);
}
}
实现类接口注册到Nacos注册中心
四、Nacos注册中心
五、小结
非常简单的一个demo,可以创建多个Provider和Consumer来实现服务之间的调用,有条件也可以搭建集群实现,官方也有类似的文档,大家也可以参考学习:nacos.io/zh-cn/docs/…