All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.opensabre.rpc.openfeign.interceptor.FeignHeaderInterceptor Maven / Gradle / Ivy

The newest version!
package io.github.opensabre.rpc.openfeign.interceptor;

import com.google.common.collect.Maps;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * spring cloud feign传递header
 *
 * @author zhoutaoo
 */
@Component
public class FeignHeaderInterceptor implements RequestInterceptor {

    /**
     * 获取request header 放入远程template中
     */
    @Override
    public void apply(RequestTemplate template) {
        getHeaders().forEach(template::header);
    }

    /**
     * 获取 request 中的所有的 header 值
     *
     * @return header map
     */
    private Map getHeaders() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        Map map = Maps.newHashMap();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy