青柠开车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

将项目的注释部分解注,即可成功集成。

posted @ 2018-09-18 16:47  青柠Loft  阅读(15534)  评论(0编辑  收藏  举报
qnloft 青柠的Blog