spring cloud gateway是spring官方最新推出的一款基于Spring Framework 5,Project Reactor和Spring Boot 2之上开发的网关。与zuul1.0不同的是,gateway是异步非阻塞的(netty+webflux实现),zuul1.0是同步阻塞请求的。gateway的数据是封装在ServerWebExchange中,zuul是存放在RequestContext里的(这里是重点,圈起来!)Gateway相对于Zuul来说,在路由的配置上更加多样化,配置更加简便。

本人最开始使用的是zuul1.0,随着版本变迁,springcloud 推出了zuul2.0以及gateway,在网上翻看了些资料,发现zuul1.0和zuul2.0看着变化似乎不大,升不升级好像都没啥影响。但是gateway就不同了,它支持webscoket的配置使用,并且响应式编程也是很值得去尝试的,话不多说,接下来简单说明下如何使用gateway搭建一个网关。

(1)首先,创建一个springboot工程,选择springboot版本2.0.5.RELEASE,springcloud 版本Finchley.RELEASE

(2)引入spring-cloud-starter-gateway的依赖,如下:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

(3)至此一个简单的gateway网关就算好了,可能在实际使用过程中还需要配置ribbon负载,hystrix熔断等等,这些就不再赘述了,如果需要观察网关的健康监控信息可以引入spring-boot-starter-actuator的依赖。

(4)gateway中支持的路由方式有before/after/between/cookie/header/host/method/path/query/RemoteAddr,个人比较经常用的就是Path Route Predicate Factory,这些路由方式的使用都可以直接在配置文件中配置使用,非常方便。举个简单例子,当我们想通过网关访问producer的服务时,配置uri为目标的地址,Path为匹配规则(服务地址)时就可以按如下进行配置使用,官网还有很多相关的事例供大家选择,这里就不一一举例了。

spring:
  cloud:
    gateway:
      routes:
      - id: producer_route
        uri: http://localhost:8081
        predicates:
        - Path=/producer/test
      - id: producer_image_route
        uri: http://localhost:8081
        predicates:
        - Path=/producer/images/**

(5)可以将gateway配置为基于在DiscoveryClient兼容服务注册中心注册的服务来创建路由,具体操作如下:

//注入discoveryClientRouteDefinitionLocator
@Bean
    public RouteDefinitionLocator discoveryClientRouteDefinitionLocator(DiscoveryClient discoveryClient, DiscoveryLocatorProperties properties) {
        return new DiscoveryClientRouteDefinitionLocator(discoveryClient, properties);
    }

//在配置文件中设置支持服务中心路由
spring.cloud.gateway.discovery.locator.enabled=true

(6)我们也可以自定义路由器,如下:

//自定义html元素过滤路由    
@Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();

        routes.route(p -> p.path("/producer/test").filters(f -> f.modifyResponseBody(String.class, String.class, "text/html",
                (exhange, in) -> {
                    System.out.println("Received :" + in);
                    String newContent = in.replaceFirst("I am a tag!", "I am a modified tag!");
                    return Mono.just(newContent);
                })).uri("http://localhost:8081/producer/test"));
        return routes.build();
    }

在zuul中我们可能都有用到动态路由功能,其实gateway也有动态路由,动态路由主要涉及RouteDefinitionWriter,ApplicationEventPublisher,RouteDefinitionRepository这几个类的应用,这个等后面再花篇幅去细说,今天就先交代到这啦~写的不好,还请见谅!有描述不对的地方欢迎大家指出,交流加?1023230607,添加时备注下,谢谢!

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐