首页 > 其他分享 >spring cloud open feign header 参数传递

spring cloud open feign header 参数传递

时间:2024-12-15 17:00:08浏览次数:6  
标签:feign spring request springframework header context org import

consumer 配置 以下内容

```java
package com.me.consumer.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 *  feign 传递  header 参数
 */
@Configuration
public class FeignRequestConfiguration {


    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                /**
                 *   从 consumer 获取 请求header参数    透传到 provider
                 */
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
                    if (servletRequestAttributes!=null){
                        HttpServletRequest request = servletRequestAttributes.getRequest();

                        Enumeration<String> headerNames = request.getHeaderNames();
                        if (headerNames != null) {
                            while (headerNames.hasMoreElements()) {
                                String name = headerNames.nextElement();
                                String values = request.getHeader(name);
                                template.header(name, values);
                            }
                        }
                    }
                }

            }
        }
        ;
    }
}

标签:feign,spring,request,springframework,header,context,org,import
From: https://blog.csdn.net/confident3/article/details/144428008

相关文章