Spring cloud Gateway介绍

本文介绍了Spring Cloud Gateway的核心概念,包括Route(路由)、Predicate(断言)和Filter(过滤)。Route是构建网关的基础,由ID、目标URI和断言、过滤器组成。Predicate允许开发人员匹配HTTP请求的各种内容,而Filter则用于在请求路由前后修改请求。文中还展示了如何在Spring Cloud Gateway配置静态和动态路由,并提供了相关的配置代码示例。同时,给出了自定义全局过滤器MyLogGateWayFilter的实现,用于记录请求信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

gateway的三大核心概念是路由、断言、过滤。

Route(路由)路由是构建网关的基本模块,它由ID,目标URI,一些列的断言和过滤器组成,如果断言为ture 则匹配该路由。

Predicate(断言),参考的是Java8的java.util.function.Predicate,开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言匹配则进行路由。

Filter(过滤)只得是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或之后对请求进行修改。

cloud-gateway-gateway9527

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springCloud</artifactId>
        <groupId>com.george.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-gateway-gateway9527</artifactId>

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!--引入自定义的api通用包,可以使用Payment支付Entity-->
        <dependency>
            <groupId>com.george.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--web Gateway不需要web依赖,会报错
        Parameter 0 of method modifyResponseBodyGatewayFilterFactory in org.springframework.cloud.gateway.config.GatewayAutoConfiguration required a bean of type 'org.springframework.http.codec.ServerCodecConfigurer' that could not be found.
        -->
        <!--        <dependency>-->
        <!--            <groupId>org.springframework.boot</groupId>-->
        <!--            <artifactId>spring-boot-starter-web</artifactId>-->
        <!--        </dependency>-->
        <!--        <dependency>-->
        <!--            <groupId>org.springframework.boot</groupId>-->
        <!--            <artifactId>spring-boot-starter-actuator</artifactId>-->
        <!--        </dependency>-->


    </dependencies>
</project>
## =========================
##       路由写死的方式
## =========================
#server:
#  port: 9527
#spring:
#  application:
#    name: cloud-gateway
#  cloud:
#    gateway:
#      routes:
#        - id: payment_routh #payment_route 路由的ID 没有固定规则但要求唯一,建议配合服务名
#          uri: http://localhost:8001  #匹配后提供服务的路由地址
#          predicates:
#            - Path=/payment/get/**  #断言,路径相匹配的进行路由
#
#        - id: payment_routh2
#          uri: http://localhost:8001
#          predicates:
#            - Path=/payment/lb/**



# =========================
#       动态路由方式
# =========================
server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true  #开启注册中心路由功能,利用微服务名进行路由
      #          lower-case-service-id: true
      routes:
        - id: payment_routh
          #          uri: http://localhost:8001
          uri: lb://cloud-payment-service # 匹配后提供服务的路由地址;
          predicates:
            - Path=/payment/get/**
#            - After=2021-01-28T16:56:10.793+08:00[Asia/Shanghai]
        - id: payment_routh2
          #          uri: http://localhost:8001
          uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/lb/**

eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://eureka7001.com:7001/eureka #单机
#      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群



package com.george.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * @author Yang Hao
 * @description
 * @date 2020-09-18 16:18
 */
@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
    public static void main(String[] args) {
        SpringApplication.run(GateWayMain9527.class);
    }
}

package com.george.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;

/**
 * @author Yang Hao
 * @description 编码的方式
 * 官网 https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gatewayfilter-factories
 * @date 2020-09-18 16:55
 */
@Configuration
public class GatewayConfig {

    /**
     * 配置一个ID为 path_route_george 的路由规则
     * 当访问地址:http://localhost:9527/guonei 时会自动转发到地址 http://news.baidu.com/guonei
     *
     * @param routeLocatorBuilder
     * @return
     */
    @Bean
    public RouteLocator customeRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {
        return routeLocatorBuilder.routes()
                .route("path_route_george", r -> r.path("/guonei").uri("http://news.baidu.com/guonei"))
                .build();
    }
}

package com.george.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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;

/**
 * @author Yang Hao
 * @description 自定义全局GlobalFilter
 * @date 2020-09-18 17:49
 */
@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 (StringUtils.isEmpty(uname)) {
            log.info("------------ 用户名 [{}] 非法 o(╥﹏╥)o", uname);
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);

    }

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

启动注册中心7001,支付服务8001和支付服务8002,启动网关。
运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值