请求头过滤器
- 传递请求ID
- 传递请求头授权信息
java
package cloud.xuxiaowei.gateway.filter;
import lombok.Setter;
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.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.function.Consumer;
/**
* 请求头 过滤器
*
* @author xuxiaowei
* @since 0.0.1
*/
@Setter
@Slf4j
@Component
public class RequestHeaderGlobalFilter implements GlobalFilter, Ordered {
public static final int ORDERED = Ordered.HIGHEST_PRECEDENCE + 20000;
private int order = ORDERED;
@Override
public int getOrder() {
return this.order;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
// 获取请求ID
String id = request.getId();
HttpHeaders headers = request.getHeaders();
// 获取请求头授权令牌
String authorization = headers.getFirst(HttpHeaders.AUTHORIZATION);
Consumer<HttpHeaders> httpHeaders = httpHeader -> {
// 向后传递请求ID
httpHeader.set("Request-Id", id);
// 向后传递请求头授权令牌
httpHeader.set(HttpHeaders.AUTHORIZATION, authorization);
};
ServerHttpRequest build = request.mutate().headers(httpHeaders).build();
return chain.filter(exchange.mutate().request(build).build());
}
}