Spring Cloud Alibaba+Nacos搭建微服务架构
1. Spring Cloud Alibaba 简介
Spring Cloud Alibaba是阿里巴巴为分布式应用提供的一站式解决方案,能够更方便快捷地搭建分布式平台,nacos拥有着替换eureka server ,spring cloud config等组件的目标和意图,旨在能够更简便快速地去管理服务、注册服务、管理配置。
2. Spring Cloud Alibaba +Nacos搭建微服务架构
集成nacos
1. 启动nacos server
nacos 官方学习文档: https://nacos.io/zh-cn/docs/quick-start.html
下载nacos: https://github.com/alibaba/nacos/releases
也可以使用如下命令安装并编译项目:
git clone https://github.com/alibaba/nacos.git
cd nacos/
mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U
项目构建完毕后,会在\nacos\distribution\target\ 目录下生成对应的包:
进入到/nacos/bin 目录下 D:\Program Files\nacos\distribution\target\nacos-server-1.4.2-SNAPSHOT\nacos\bin:
执行命令 startup.cmd -m standalone, 以单例模式启动nacos服务器:
cd D:\Program Files\nacos\distribution\target\nacos-server-1.4.2-SNAPSHOT\nacos\bin
d:
startup.cmd -m standalone
启动成功后,会出现如下logo:
访问: http://192.168.31.166:8848/nacos/index.html, 用户名和密码都是nacos,登录成功后,就可以看到如下的nacos首页:
2. 微服务客户端集成spring cloud alibaba +nacos server
自己建的项目相当于一个微服务客户端,在本例中就是一个nacos客户端,要想将服务注册到nacos server中,我们需要做三件事
1)在pom.xml文件中添加依赖
nacos客户端依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
pom.xml文件完整配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.exam.springcloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-cloud-alibaba</name>
<description>project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring.cloud.alibaba.version>2.2.1.RELEASE</spring.cloud.alibaba.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId