前端需要记录每个微服务的地址,不利于项目上线更换地址。增加网关后,前端只需要请求网关,由网关帮忙路由到各个微服务。
但是网关如何知道每个微服务的地址呢?这个时候就要借助注册中心。每个微服务都将自己注册到注册中心,网关也将自己注册到注册中心;注册中心会记录下每个微服务的地址,网关从注册中心读取服务列表,路由到具体的微服务。
创建网关工程
创建learning-online-gateway
模块,其Parent
为learning-online-parent
,但其父目录为learning-online
。
其pom依赖如下:
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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.swx</groupId> <artifactId>learning-online-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath>../learning-online-parent/pom.xml</relativePath> </parent>
<artifactId>learning-online-gateway</artifactId>
<properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> </dependencies> </project>
|
在com.swx.gateway
包下创建启动类GatewayApplication
,内容如下:
@SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
|
配置文件bootstrap.yml
放在资源目录resources
下,内容如下:
bootstrap.ymlspring: application: name: gateway cloud: nacos: discovery: server-addr: 127.0.0.1:8848 namespace: learning-online-dev group: learning-online-project config: server-addr: 127.0.0.1:8848 namespace: learning-online-dev group: learning-online-project file-extension: yaml refresh-enabled: true shared-configs: - data-id: logging-${spring.profiles.active}.yaml group: learning-online-common refresh: true profiles: active: dev
|
日志文件 log4j2-dev.xml同其他微服务。
Nacos配置
打开Nacos管理界面,添加新的配置文件:http://ip:8848/nacos
命名空间选择learning-online-dev
创建系统管理工程配置:gateway-dev.yaml