FeignBasicAuthRequestInterceptor.java
java
package com.codex.terry.configuration;
import feign.RequestInterceptor;
import feign.RequestTemplate;
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;
/**
* 文件名称: FeignBasicAuthRequestInterceptor.java
* 编写人: yh.zeng
* 编写时间: 2024/7/8 14:04
* 文件描述: 将请求的Header添加到OpenFeign发起的请求中
*/
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor
{
private HttpServletRequest getHttpServletRequest() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
return attributes.getRequest();
}
@Override
public void apply(RequestTemplate template) {
HttpServletRequest request = getHttpServletRequest();
// 遍历所有header,添加到Feign的RequestTemplate中
Enumeration<String> headers = request.getHeaderNames();
while(headers.hasMoreElements()){
String headerName = headers.nextElement();
String headerValue = request.getHeader(headerName);
template.header(headerName, headerValue);
}
}
}
1、方式一:
FeignConfig.java
java
package com.codex.terry.configuration;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 文件名称: FeignConfig.java
* 编写人: yh.zeng
* 编写时间: 2024/7/8 14:09
* 文件描述: 将请求的Header添加到OpenFeign发起的请求中
*/
@Configuration
public class FeignConfig
{
@Bean
public RequestInterceptor requestInterceptor(){
return new FeignBasicAuthRequestInterceptor();
}
}
HelloWorldFeignClient.java
java
package com.codex.terry.feignclient;
import com.codex.terry.configuration.FeignClientLogConfiguration;
import com.codex.terry.configuration.FeignConfig;
import com.codex.terry.feignclient.fallback.HelloWorldFeignClientFallback;
import com.codex.terry.feignclient.fallbackfactory.HelloWorldFeignClientFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 文件名称: HelloWorldFeignClient.java
* 编写人: yh.zeng
* 编写时间: 2024/6/25 16:05
* 文件描述: todo
*/
//@FeignClient(name="helloworld", configuration = FeignClientLogConfiguration.class)
//@FeignClient(name="helloworld", fallback = HelloWorldFeignClientFallback.class)
@FeignClient(name="helloworld",configuration = FeignConfig.class ,fallbackFactory = HelloWorldFeignClientFallbackFactory.class)
public interface HelloWorldFeignClient
{
@RequestMapping("/sayHello")
String sayHello();
@RequestMapping(value="/say/{msg}")
String say(@PathVariable("msg") String msg);
}
2、方式二:
XML
feign:
client:
config:
helloworld:
loggerLevel: full
default:
requestInterceptors:
- com.codex.terry.configuration.FeignBasicAuthRequestInterceptor