springcloud fegin獲取request header解決方案

weixin_33782386發表於2018-04-17

假設現在有A服務,B服務,外部使用RESTApi請求呼叫A服務,在請求頭上有token欄位,A服務使用完後,B服務也要使用,如何才能把token也轉發到B服務呢?這裡可以使用Feign的RequestInterceptor,但是直接使用一般情況下HttpServletRequest上下文物件是為空的,這裡要怎麼處理,請看下文。

9028759-1f44811b9fb44bb1.png
springcloud

演示

A服務FeginInterceptor

@Configuration
public class FeginInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        Map<String,String> headers = getHeaders(getHttpServletRequest());
        for(String headerName : headers.keySet()){
            requestTemplate.header(headerName, getHeaders(getHttpServletRequest()).get(headerName));
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

}

重點配置
A服務配置bootstrap.yml

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: SEMAPHORE

A服務build.gradle

buildscript {
    ext{
        springBootVersion = '1.5.9.RELEASE'
    }

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath "io.spring.gradle:dependency-management-plugin:0.5.6.RELEASE"
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: "io.spring.dependency-management"
version = '0.0.1-SNAPSHOT'
group 'com.dounine.test'

sourceCompatibility = 1.8

repositories {
    mavenLocal()
    mavenCentral()
}

ext {
    springCloudVersion = 'Dalston.SR2'
}

dependencies {
    compile('org.springframework.cloud:spring-cloud-starter-config')
    compile('org.springframework.cloud:spring-cloud-starter-eureka')
    compile('org.springframework.cloud:spring-cloud-starter-feign')
    compile group: 'org.aspectj', name: 'aspectjweaver', version: '1.8.13'
    compile('org.springframework.boot:spring-boot-starter-data-redis')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

B服務Action

    @Autowired
    private HttpServletRequest servletRequest;

    public String test() {
        return servletRequest.getHeader("token");
    }

B服務問題

如若B服務也要將header請求轉發到其它服務,將A服務的配置也應用到B服務上即可

相關文章