欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【聊一聊】SpringCloudGateway的Filter

程序员文章站 2024-03-17 08:13:52
...

前言:

本篇博客主要是展示Gateway的Filter的使用及自定义过滤器进行类比,从而更好的,掌握Filter相关技术。


Gateway的Filter声明周期

  • pre
  • post
    Gateway的Filter种类
  • GatewayFilter
  • GlobalFilter

常用Gateway的Filter

【聊一聊】SpringCloudGateway的Filter

自定义过滤器:工作中使用最多


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

/**
 * @ClassName : MyLogGateWayFilter
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-05-21 18:24
 */
@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.equals(null)){
            log.info("******** 用户名为null,非法用户,┭┮﹏┭┮");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

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


测试

【聊一聊】SpringCloudGateway的Filter

  • 正确访问
    【聊一聊】SpringCloudGateway的Filter
    -错误访问
    【聊一聊】SpringCloudGateway的Filter