GatewayFilter 需要配置某个路由,才能过滤。如果需要使用全局路由,需要配置 Default Filters。
4 自定义网关过滤器(重点)
- package com.it.filter;
-
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.cloud.gateway.filter.GlobalFilter;
- import org.springframework.core.Ordered;
- import org.springframework.core.io.buffer.DataBuffer;
- import org.springframework.http.HttpHeaders;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.server.reactive.ServerHttpRequest;
- import org.springframework.http.server.reactive.ServerHttpResponse;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import reactor.core.publisher.Mono;
-
- import java.net.URI;
- import java.util.HashMap;
-
- /**
- * 定义了一个过滤器,
- * 需要给该过滤器指定执行顺序,通常一个项目中有多个过滤器,组成过滤器的责任链模式。
- */
- @Component
- public class MyGlobalFilter implements GlobalFilter, Ordered {
-
- /**
- * 这个就是全部过滤的方法
- * 常用责任链模式
- * @param exchange
- * @param chain
- * @return
- */
- @lombok.SneakyThrows
- @Override
- public Mono
filter(ServerWebExchange exchange, GatewayFilterChain chain) { - //针对请求的过滤,拿到请求 header url 参数
- ServerHttpRequest request = exchange.getRequest();
-
- String uri = request.getURI().getPath();
- System.out.println(uri);
- HttpHeaders headers = request.getHeaders();
- System.out.println(headers);
- String name = request.getMethod().name();
- System.out.println(name);
- String hostName = request.getRemoteAddress().getHostName();
- System.out.println(hostName);
-
- //响应相关的
- ServerHttpResponse response = exchange.getResponse();
-
- //放行,转入下一个过滤器
- // return chain.filter(exchange);
-
- //不放行
- response.getHeaders().set("content-type","application/json;charset=utf-8");
- //组装业务返回值
- HashMap
- map.put("code", HttpStatus.UNAUTHORIZED.value());
- map.put("msg","你未授权!");
- ObjectMapper objectMapper = new ObjectMapper();
- //因为返回类型为Mono
,所以需要把map转换成一个字节 - byte[] bytes = objectMapper.writeValueAsBytes(objectMapper);
- //通过buffer工厂将字节数组包装成一个数据包
- DataBuffer wrap = response.bufferFactory().wrap(bytes);
- return response.writeWith(Mono.just(wrap));
-
-
- }
-
- /**
- * 指定过滤器执行顺序的方法
- * 越小越先执行
- * @return
- */
- @Override
- public int getOrder() {
- return -1;
- }
- }