此篇文章讲解在之前使用的nacos的基础上整合Gateway,之前整合的nacos项目不在赘述
环境准备
1、启动nacos
2、准备服务A启动后注册到注册中心nacos中
下面创建gateway
1、创建一个spring boot项目,pom文件如下:
<?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.1.15.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mythical</groupId>
<artifactId>rosefinch-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gateway</name>
<description>小程序网关</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 整合springCloud Alibaba -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>0.9.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、application.yml文件如下:
server:
port: 8083
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848
#指定 namespace,此id在nacos中创建一个命名空间即可生成,一定要与A服务中一致,不然gateway路由不到A服务
namespace: 4c6a61af-7019-4bda-a83b-e4ebb8edcdd4
#指定集群
cluster-name: NJ
gateway:
discovery:
locator:
#让gateway通过服务发现组件找到其他的微服务
enabled: true
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
3、启动gateway服务
4、访问验证
rosefinch-web是A的服务名称
user/getAllUser是A的方法路径
http://127.0.0.1:8083/rosefinch-web/user/getAllUser
5、结果:
通过gateway访问到了A服务
这个只是实现了一下路由功能,后续会完善gateway的一些项目应用