6、spring-cloud-gateway

发布于:2025-04-21 ⋅ 阅读:(11) ⋅ 点赞:(0)

依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
    </dependencies>

配置文件

server:
  port: 8080

spring:
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

    gateway:
      routes:
        - id: ms1
          uri: lb://ms1
          predicates:
            - Path=/ms1/**
          filters:
            - RewritePath=/ms1/?(?<segment>.*),/$\{segment}

        - id: ms2
          uri: lb://ms2
          predicates:
            - Path=/ms2/**
          filters:
            - RewritePath=/ms2/?(?<segment>.*),/$\{segment}

        - id: ms3
          uri: lb://ms3
          predicates:
            - Path=/ms3/**
          filters:
            - RewritePath=/ms3/?(?<segment>.*),/$\{segment}

配置类

可自定义断言工厂、拦截器工厂、全局拦截器

自定义全局拦截器

@Slf4j
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().toString();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("请求【{}】开始,时间:{}", uri, LocalDateTime.now());
        // 放行
        Mono<Void> mono = chain
                .filter(exchange)
                .doFinally((result) -> {
                    stopWatch.stop();
                    log.info("请求【{}】结束,时间:{},耗时:{}s", uri, LocalDateTime.now(), stopWatch.getTotalTimeSeconds());
                });
        return mono;
    }

    @Override
    public int getOrder() {
        // 数字越小,优先级越高
        return 0;
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到