网关项目
网关项目需要单独新建gateway工程,并在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.9.RELEASE</version>
<relativePath/> <!--lookup parent from
repository -->
</parent>
<groupId>com.example.gateway</groupId>
<artifactId>gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gateway</name>
<description>Gateway project for Spring
Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<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>
<artifactId>junit
vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter
gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter
validation</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud
dependencies</artifactId>
<version>Hoxton.RC2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot
maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
设置路由断言配置,具体信息如下:
server:
port: 80
spring:
application:
name: gateway
cloud:
gateway:
routes:
-id: promotion_route
uri: http://127.0.0.1:8081/
predicates:
-Path=/api/**
启动网关服务与促销活动微服务项目,通过网关的路由断言,直接访问http://
localhost/api/pushPromotion?id=1接口,返回数据如下:
{
code: "S00000",
msg: "success",
result: {
id: 3,
name: "会员促销活动",
beginTime: 1614822680,
endTime: 1617176808,
prize: "3天免费会员"
}
}
可以看到,与直接访问微服务接口的返回数据一致。
项目部署
(1)采用Spring Boot的Maven打包插件,将3个项目分别打包为promotion.jar、
microservice-promotion.jar和gateway.jar。
(2)采用java -jar ***.jar命令分别启动3个项目,可以将它们部署在虚拟机或云平台之上。