青檸開車Spring Cloud(六) —— Spring Cloud Gateway與zuul使用對比


項目源碼github地址

補充

  • 使用網關前項目架構
    backendforfrontend

  • 使用網關后項目架構
    apigateway

Gateway簡介

官方文檔官方demo

spring-cloud-Gatewayspring-cloud的一個子項目。而zuul則是netflix公司的項目,只是spring將zuul集成在spring-cloud中使用而已。
還有一種說法是因為zuul2連續跳票和zuul1的性能表現不是很理想,所以催生了spring孵化Gateway項目。

快速入門

spring-cloud創建spring-cloud-gateway子模塊項目

Gateway 項目基本配置

  • pom.xml中加入jar包

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!-- 集成eureka -->
    <!--<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>-->
</dependencies>
  • application.properties配置

server.port= 8562
spring.application.name=gateway

# 日志打印的級別
logging.level.org.springframework.cloud.gateway = debug

#集成eureka時開啟
#spring.cloud.gateway.discovery.locator.enabled=true
#集成eureka
#eureka.client.serviceUrl.defaultZone= http://localhost:8761/eureka/
  • springboot啟動類
/**
 * @author : R&M www.rmworking.com/blog
 *         2018/9/18 11:15
 *         spring-cloud
 *         org.qnloft.gateway
 */
//@EnableEurekaClient
@SpringBootApplication
public class GateWayApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(GateWayApplication.class, args);
    }
}

加入gateway網關配置

看完上面的內容,小伙伴們應該發現,這和普通的springboot項目有毛區別啊~~~,別着急,讓我帶領大家來揭開gateway的面紗!

spring-cloud-gateway有兩種配置方式,一種是在application.yml中配置,一種是使用@Bean對象注入。(注意:二者選其一)

  • application.yml方式

spring:
  cloud:
    gateway:
      routes:
      - id: WEB
        uri: http://127.0.0.1:8661
        predicates:
        - Path=/web/{segment}
        filters:
        - SetPath=/{segment}
  • @Bean對象注入配置方式

GateWayApplication.java中加入如下內容:


@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route("WEB", r -> r.path("/web/{segment}")
                    .filters(f -> f.setPath("/{segment}"))
                    .uri("http://127.0.0.1:8661"))
            .build();
}

簡要說明:

  • id:路由的id,參數配置不要重復,如不配置,gateway會使用生成一個uuid代替。
  • uri:路由的目標地址。注意:uri地址后面不要加 " / "
  • Path:配置路由的路徑。比如:/web/{segment}則表示當訪問http://127.0.0.1:8562/web/**時候路由的指定的uri上面
  • SetPath:在發起請求時,在路由請求路徑后面加上web/后面的內容。如果不配置,將無法路由地址后綴/web/index,只能路由/web

測試:現在我們啟動spring-web項目和spring-cloud-gateway項目,瀏覽器訪問:http://127.0.0.1:8562/web/index ,當出現和 http://127.0.0.1:8661/index 相同的內容既證明網關配置成功。

關於@Bean方式更多配置請參見:這里

集成Eureka

將項目的注釋部分解注,即可成功集成。


免責聲明!

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



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