SpringCloud-服务网关GateWay的使用

GateWay简介

SpringCloud GateWay 是Spring Cloud的一个全新项目,基于 Spring5.0 + SpringBoot2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的API路由管理方式。
SpringCloud GateWay 作为Spring Cloud 生态系统中的网关,目标是替代zuul,在Spring Cloud 2.0以上版本中,没有对新版本的Zuul2.0以上最新高性能版本进行集成,仍然还是使用的Zuul 1.X非Reactor模式的老版本。而为了提升网关性能,SpringCloud GateWay 是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式框架Netty。
Spring Cloud GateWay的目标提供统一的路由方式且基于Filter链的方式提供了网关的基本功能,例如:安全,监控/指标,和限流。

具体使用:

1.在pom中引入下面的依赖

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

2.在application.yml中配置下面的信息:

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  #下面的配置是对8001微服务套个网关
  cloud:
    gateway:
      routes:
        - id: payment_routh     #payment_route   #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001      #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/**    #断言,路径相匹配的进行路由

        - id: payment_routh2    #payment_route  #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001      #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**    #断言,路径相匹配的进行路由

eureka:
  instance:
    hostname: cloud-gateway-service
  client:   #服务提供方provider注册进eureka服务列表内
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://eureka7001.com:7001/eureka

tips: 完成上面的配置,即可通过访问http://localhost:9527/payment/get/2来得到访问http://localhost:8001/payment/get/2相同的结果,同理,访问http://localhost:9527/payment/lb的结果也和http://localhost:8001/payment/lb一样!


除了上面的yml文件中可以配置路由外,GateWay还支持硬编码方式,比如下面的编码是对http://news.baidu.com/guonei套一层网关的壳子,这跟restTemplate服务调用功能差不多,仅作者本人认为!

package org.lzl.springcloud.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GateWayConfig {

    //下面是GateWay配置路由的另一种方式(前一种方式是在yml中编写)
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
        //http://news.baidu.com/guonei
        routes.route("path_route_lzl",r -> r.path("/guonei").uri("http://news.baidu.com/guonei")).build();
        return routes.build();
    }
    @Bean
    public RouteLocator customRouteLocator2(RouteLocatorBuilder routeLocatorBuilder){
        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
        //http://news.baidu.com/guoji
        routes.route("path_route_lzl2",r -> r.path("/guoji").uri("http://news.baidu.com/guoji")).build();
        return routes.build();
    }

}

上面是GateWay的初级使用,下面是进阶内容:





配置动态路由

说一下为什么要配置动态路由?在分布式架构的系统中,一般服务提供方不只一个,而要想对多个Provider进行封装网关路由,就必须使用动态路由这种方式。

主要是修改application.yml中的配置,配置可以参考一下下面的:

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  #下面的配置是对8001微服务套个网关
  cloud:
    gateway:
      discovery:        #(!!!配置动态路由加上这一行)
        locator:        #(!!!配置动态路由加上这一行)
          enable: true  #(!!!配置动态路由加上这一行)开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh     #payment_route   #路由的ID,没有固定规则但要求唯一,建议配合服务名
#          uri: http://localhost:8001      #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service  #(!!!配置动态路由时,用这个取代上面的一行)匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/**    #断言,路径相匹配的进行路由

        - id: payment_routh2    #payment_route  #路由的ID,没有固定规则但要求唯一,建议配合服务名
#          uri: http://localhost:8001      #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service  #(!!!配置动态路由时,用这个取代上面的一行)匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**    #断言,路径相匹配的进行路由


eureka:
  instance:
    hostname: cloud-gateway-service
  client:   #服务提供方provider注册进eureka服务列表内
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://eureka7001.com:7001/eureka

配置好之后,假设8001端口的微服务和8002端口的微服务名都是spring.application.name=cloud-payment-service,通过访问http://localhost:9527/payment/lb发现,调用时默认是使用了负载均衡的轮循算法。





predicate断言

断言的作用对合法数据进行放行,从而达到限流的作用来减轻服务器的压力。

使用案例:
1.Cookie

          predicates:
            - Cookie=username,zzyy
#    ...........................

比如用上面的cookie断言,就要求请求参数中必须有username=zzyy的cookie
我们使用curl工具进行测试,下面的没有指定cookie时的报错!
在这里插入图片描述
加上cookie后,即可返回正常结果!
在这里插入图片描述
2.时间断言,下面的案例是必须在该时间以后!

          predicates:
            - After=2021-03-19T15:46:44.179+08:00[Asia/Shanghai]
#    ...........................

那么怎么获取这种时间格式呢,可以通过下面的代码方法来获取:

import java.time.ZonedDateTime;

public class T2 {
    public static void main(String[] args) {
        ZonedDateTime zbj = ZonedDateTime.now();
        System.out.println(zbj);//2021-03-19T14:46:44.179+08:00[Asia/Shanghai]
    }
}

如果不符合时间规则,访问其微服务会出现下面的异常界面:
在这里插入图片描述

如果想了解其他的断言方法,看看其他人的博客吧!




Filter过滤器

过滤器分为GateWay过滤器和全局过滤器,个人认为,过滤器和断言的作用差不多,下面的GateWay过滤器的使用方法,就是在yml中加入下面的filter的相关配置:

        - id: payment_routh2    #payment_route  #路由的ID,没有固定规则但要求唯一,建议配合服务名
#          uri: http://localhost:8001      #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service  #(!!!配置动态路由时,用这个取代上面的一行)匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**    #断言,路径相匹配的进行路由
#            - Method=GET
#            - After=2021-03-19T15:46:44.179+08:00[Asia/Shanghai]
#            - Header=X-Request-Id,\d+   #请求头要有X-Request-Id属性并且值为整数的正则表达式
#            - Cookie=username,zzyy
          filters:   #gatewayfilter
            - AddRequestParameter=red,blue

而全局过滤器只需要写上下面的代码,通过@Component加入到IOC容器:

package org.lzl.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("******come in MyLogGateWayFilter:  "+new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if(uname==null) {
            log.info("******用户名为null,非法用户,o(╥﹏╥)o");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

全局过滤器要求,请求参数中必须夹带uname,如果不携带的话,是无法正常访问的,比如访问http://localhost:9527/payment/get/2,得到的页面是:
在这里插入图片描述
后台打印:
在这里插入图片描述
而访问http://localhost:9527/payment/get/2?uname=uu是可以正常访问的:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

键盘歌唱家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值