11.gateway网关


1.简介

这个博客详细

https://blog.csdn.net/rain_web/article/details/102469745/

2.代码部分与结果演示

a.导入gateway依赖

        
            org.springframework.cloud
            spring-cloud-starter-gateway
        

b.yml配置

spring:
  application:
    name: cloud-gataway                     # 开启服务后,该服务的别名
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: com.mysql.cj.jdbc.Driver              # mysql驱动包
    url: jdbc:mysql://11.111.111.111:3306/my?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 1234
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # 在注册中心能够注册路由
      # 使用yml中配置路由

      routes:
        - id: payment_routh
          uri: lb://CLOUD-PAYMENT-SERVICE   #  lb://CLOUD-PAYMENT-SERVICE  ;lb表示轮询,CLOUD-PAYMENT-SERVICE在eureka中的别名
          predicates:              # 断言,加入一些限定条件
            - Path=/port
            # - After=2022-05-07T20:30:07.417+08:00[Asia/Shanghai] #断言,时间在这之后才能执行

        - id: payment_routh2
          uri: https://spring.io
          predicates:
            - Path=/projects/spring-cloud-gateway

yml改用java代码配置,添加一个配置类

@Configuration
public class GatewayConfig {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("path_route", r -> r.path("/")
                        .uri("https://www.baidu.com"))
                .build();
    }
}

功能1:隐藏真实服务端端口号

用8001端口查询。服务器本身就是8001端口

 用网关9527端口查询

b:功能2 过滤作用

@Component
@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获得第一个请求参数,如http://localhost:9527/port?username=cc中username
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if (username == null){
            System.out.println("非法用户");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            // 获取请求头中的headers中的authorization,也就是token的键值对
            String authorization = exchange.getRequest().getHeaders().get("authorization").get(0);
            String token = StrUtil.removePrefix( authorization,"Bearer").trim();

            System.out.println("token:" + token);
            return exchange.getResponse().setComplete();
        }
        log.info("自定义全局过滤");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}