Spring cloud整合OpenFeign
一. 什么是 OpenFeign
想知道什么是OpenFeign,首先要知道何为Feign?
Feign是SpringCloud组件中一个轻量级RESTFul的HTTP客户端。
Feign内置了Ribbon实现客户端请求的负载均衡。但是Feign是不支持Spring MVC注解的,所以便有了OpenFeign,OpenFeign在Feign的基础上支持Spring MVC注解比如 @RequestMapping等。
OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,通过动态代理生成实现类,实现类做负载均衡并调用其他服务。
二. 项目引入OpenFeign
1. 引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
2. Feign调用
@FeignClient("micro-auth")
public interface MicroAuthService {
@PostMapping(value = "/oauth/token")
JsonData getAccessToken(@RequestParam("parameters") Map<String, String> parameters);
}
3. 配置feign底层http调用
feign:
okhttp:
enabled: true
4. feign请求头丢失token,请求头根据实际使用修改
@Configuration
public class OpenFeignConfig {
/**
* feign调用丢失token解决方式,新增拦截器
* @return
*/
@Bean
public RequestInterceptor requestInterceptor(){
return template -> {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if(attributes!=null){
HttpServletRequest httpServletRequest = attributes.getRequest();
if(httpServletRequest == null){
return;
}
String token = httpServletRequest.getHeader("Access-Token");
template.header("Access-Token",token);
}
};
}
}