網關
發送請求需要知道商品服務的地址,如果商品服務器有100服務器,1號掉線后,
還得改,所以需要網關動態地管理,他能從注冊中心中實時地感知某個服務上
線還是下線。
請求也要加上詢問權限,看用戶有沒有權限訪問這個請求,也需要網關。
所以我們使用spring cloud的gateway組件做網關功能。
網關是請求瀏覽的入口,常用功能包括路由轉發,權限校驗,限流控制等。springcloud gateway取代了zuul網關。
三大核心概念:
Route: The basic building block of the gateway. It is defined by an ID, a 
destination URI, a collection of predicates斷言, and a collection of filters. 
A route is matched if the aggregate predicate is true.
發一個請求給網關,網關要將請求路由到指定的服務。
路由有id,
目的地uri,
斷言的集合,
匹配了斷言就能到達指定位置,
Predicate斷言:
This is a Java 8 Function Predicate. The input type is a Spring 
Framework ServerWebExchange. This lets you match on anything from the 
HTTP request, such as headers or parameters.就是java里的斷言函數,匹配請求里的任何信息,包括請求頭等
Filter:
These are instances of Spring Framework GatewayFilter that have been 
constructed with a specific factory. Here, you can modify requests and
responses before or after sending the downstream request.
過濾器請求和響應都可以被修改。
客戶端發請求給服務端。中間有網關。先交給映射器,如果能處理就交給handler
處理,然后交給一系列filer,然后給指定的服務,再返回回來給客戶端。
12.1 創建模塊gulimall-gateway
<dependency>
            <groupId>com.zyn.glmall</groupId>
            <artifactId>glmall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
</dependency>
1 在pom.xml引入
版本環境需保持一致
<spring-boot.version>2.1.8.RELEASE</spring-boot.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
2 開啟注冊服務發現@EnableDiscoveryClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
public class GulimallGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GulimallGatewayApplication.class, args);
    }
}
3 配置nacos注冊中心地址applicaion.properties
spring.application.name=glmall-gateway
spring.cloud.nacos.discovery.server-addr=192.168.11.1:8848
server.port=88
4 bootstrap.properties 填寫配置中心地址
spring.application.name=glmall-coupon
spring.cloud.nacos.config.server-addr=192.168.11.1:8848
spring.cloud.nacos.config.namespace=a791fa0e-cef8-47ee-8f07-5ac5a63ea061
5 nacos里創建命名空間gateway,然后在命名空間里創建文件glmall-gateway.yml
spring:
    application:
        name: glmall-gateway
6 在項目里創建application.yml
spring:
  cloud:
    gateway:
      routes:
        - id: baidu_route
          uri: http://www.baidu.com
          predicates:
            - Query=url,baidu

        - id: test_route
          uri: http://www.qq.com
          predicates:
            - Query=url,qq
測試 localhost:8080?url=baidu # 跳到百度頁面
測試 localhost:8080?url=baidu # 跳到qq頁面