gateway-快速入門


搭建網關服務的步驟:

1.創建新的module-gateway module,引入SpringCloudGateway的依賴和nacos的服務發現依賴:

<dependencies>
    <!--nacos服務注冊發現依賴-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <!--網關gateway依賴-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
</dependencies>

 

2.在application.yml編寫路由配置及nacos地址

server:
  port: 10010
spring:
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: nacos:8848 # nacos地址
    gateway:
      routes: ##網關路由配置
        - id: user-service # 路由標識,自定義,只要唯一即可
          uri: lb://userservice # 路由的目標地址,lb就是負載均衡,后面跟服務名稱
          predicates: # 路由斷言,也就是判斷請求是否符合路由規則的條件
            - Path=/user/** # 這個是按照路徑匹配,只要以/user/開頭就符合要求
        - id: order-service
          uri: lb://orderservice
          predicates:
            - Path=/order/**
      default-filters:
        - AddRequestHeader=Truth,Itcast is freaking awesome!

 

3.啟動網關-GatewayApplication.java

4.通過網關訪問服務

http://localhost:10010/user/1
{"id":2,"username":"文二狗","address":"陝西省西安市"}

http://localhost:10010/order/101
{"id":101,"price":699900,"name":"Apple 蘋果 iPhone 12 ","num":1,"userId":1,"user":{"id":1,"username":"柳岩","address":"湖南省衡陽市"}}

5.總結
5.1.網關搭建步驟:
a.創建項目,引入nacos服務發現和gateway依賴
b.配置application.yml,包括服務基本信息、nacos地址、路由

5.2.路由配置包括:
路由id:路由的唯一標示
路由目標(uri):路由的目標地址,http代表固定地址,lb代表根據服務名負載均衡
路由斷言(predicates):判斷路由的規則,
路由過濾器(filters):對請求或響應做處理


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM