【聊一聊】SpringCloudGateway的Filter

前言:

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


Gateway的Filter声明周期

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

常用Gateway的Filter

【聊一聊】SpringCloudGateway的Filter_第1张图片

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


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_第2张图片

  • 正确访问
    【聊一聊】SpringCloudGateway的Filter_第3张图片
    -错误访问
    【聊一聊】SpringCloudGateway的Filter_第4张图片

你可能感兴趣的:(Spring,#)