import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.util.regex.Pattern;

@Configuration
public class FeignContextInterceptor implements RequestInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(FeignContextInterceptor.class);

    private static final Pattern INVALID_HEADER_CHARS = Pattern.compile("[\\r\\n\\t]");

    private String sanitizeHeaderValue(String value) {
        if (value == null) {
            return null;
        }
        return INVALID_HEADER_CHARS.matcher(value).replaceAll("");
    }

    @Override
    public void apply(RequestTemplate template) {
        RequestContext ctx = ContextHolder.get();
        if (ctx == null) {
            logger.warn("Feign拦截器:ContextHolder为空,无法传递上下文信息");
            return;
        }
        if (ctx.getCustomerId() != null) {
            template.header("customerId", sanitizeHeaderValue(ctx.getCustomerId()));
        }
        if (ctx.getTelephone() != null) {
            template.header("telePhone", sanitizeHeaderValue(ctx.getTelephone()));
        }
        if (ctx.getUserCode() != null) {
            template.header("userCode", sanitizeHeaderValue(ctx.getUserCode()));
        }
      
    }
}

更多推荐