Configuration of Spring Cloud Gateway custom filter

Spring Cloud Gateway Filter (filter)

Refers to the strength of GatewayFilter in the Spring framework. Using filters, the team request can be modified before or after the request is routed.

Filter official website address: Spring Cloud Gateway

Spring Cloud Gateway has its own filters, there are nearly 50 kinds, but when working, you usually write your own custom filters, which are generally used for complete log  records (such as adding and deleting logs to avoid wrangling). right

Custom filter code implementation case

1. Build a filter class, MyLogGateWayFilter and add components   with @Component . This class follows GlobalFilter, Ordered and rewrites two methods

Just write the logic in the filter method. What I write here is to judge whether the request parameter has uname. If it is empty, no access will be given. If there is a value, it will be released. Here you can write logic such as global logging.

/**
 * @author Liuxiaowei
 * @date 2022年08月12日23:22
 */
//自定义过滤器
@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("****************come in MyLogGateWayFilter" + new Date());
        //类似于获取httpRquest对象
        ServerHttpRequest request = exchange.getRequest();
        //获取请求参数
        String uname = request.getQueryParams().getFirst("uname");
        if (uname == null) {
            log.info("************用域名为null,非法用户权限不够");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    //加载过滤器顺序,数字越小越高优先级
    @Override
    public int getOrder() {
        return 0;
    }
}

success effect

 

 

Guess you like

Origin blog.csdn.net/weixin_46310452/article/details/126313085