Spring Cloud 微服務三: API網關Spring cloud gateway


前言:前面介紹了一款API網關組件zuul,不過發現spring cloud自己開發了一個新網關gateway,貌似要取代zuul,spring官網上也已經沒有zuul的組件了(雖然在倉庫中可以更新到,但主頁上已經沒有了),而且zuul1.x的性能據說也一般,所以本章將引入spring cloud原生網關產品。本章繼續前面的內容,前情回顧請參考:

Spring Cloud 微服務一:Consul注冊中心

Spring Cloud 微服務二:API網關spring cloud zuul

  • Spring cloud gateway概覽
  • Spring cloud gateway,Spring Cloud Gateway是由spring官方基於Spring5.0,Spring Boot2.0,Project Reactor等技術開發的網關.該項目提供了一個構建在Spring Ecosystem之上的API網關,旨在提供一種簡單而有效的途徑來發送API,並向他們提供交叉關注點,例如:安全性,監控/指標和彈性.
  • 集成gateway
    • 在上一個項目的基礎上新建一個module,名稱api-gateway,pom中添加如下依賴,其中gateway是spring cloud網關組件,consul用於集成注冊中心功能
            <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-gateway</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-consul-discovery</artifactId>
              </dependency>

       

    • 啟動類保持默認即可
      @SpringBootApplication
      public class ApiGatewayApplication {
          public static void main(String[] args) {
              SpringApplication.run(ApiGatewayApplication.class, args);
          }
      }

       

    • 主要在於配置文件,配置文件中定義了路由規則以及注冊中心的相關配置,以下的配置,會將http://localhost:8088下的所有請求重定向到http://localhost:10086
      server:
        port: 8088
      debug: true
      
      spring:
        application:
          name: api-gateway
        cloud:
          gateway:
            routes:
              - id: user_route
                uri: http://localhost:10086
                predicates:
                  - Path=/*
          consul:
            host: localhost
            port: 8500
            discovery:
              register: false

       

    • 啟動user-service,api-gateway,在瀏覽器訪問:http://localhost:8088/all,顯示服務的內容,調用成功!


免責聲明!

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



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