package com.sckw.gateway.filter;

import com.sckw.gateway.utils.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @desc: 给请求增加TraceId
 * @author: yzc
 * @date: 2023-08-22 14:20
 */
@Component
@Slf4j
public class TraceFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //链路追踪id
        String traceId = UuidUtils.getUuid();
        MDC.put("traceId", traceId);
        ServerHttpRequest request = exchange.getRequest().mutate()
                .headers(h -> h.add("traceId", traceId))
                .build();
        ServerWebExchange build = exchange.mutate().request(request).build();
        return chain.filter(build);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
