什么是網關
背景
單體
項目中,前端只用訪問指定的一個端口8080,就可以得到任何想要的數據
微服務項目中,ip是不斷變化的,端口是多個的
解決方案:網關
網關:就是網絡的關口,負責請求的
路由、轉發、身份校驗
。
前段還是訪問之前的端口8080即可
后端對于前端來說是透明的
網關的兩種實現
網關是一種開發規范,實際的實現有兩種:
- 官方
- 網飛公司
步驟
maven坐標
在hm-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 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>hmall</artifactId><groupId>com.heima</groupId><version>1.0.0</version></parent><modelVersion>4.0.0</modelVersion><artifactId>hm-gateway</artifactId><properties><maven.compiler.source>11</maven.compiler.source><maven.compiler.target>11</maven.compiler.target></properties><dependencies><!--common--><dependency><groupId>com.heima</groupId><artifactId>hm-common</artifactId><version>1.0.0</version></dependency><!--網關--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!--nacos discovery--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!--負載均衡--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency></dependencies><build><finalName>${project.artifactId}</finalName><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
啟動類
在hm-gateway模塊的com.hmall.gateway包下新建一個啟動類:
package com.hmall.gateway;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class GatewayApplication {public static void main(String[] args) {SpringApplication.run(GatewayApplication.class, args);}
}
測試
啟動
GatewayApplication
,以 http://localhost:8080 拼接微服務接口路徑來測試。例如:
http://localhost:8080/items/page?pageNo=1&pageSize=1