您的位置:首页 > 教程文章 > 编程开发

OpenFeign调用服务请求头丢失Token的解决

:0 :2021-10-19 22:19:55

OpenFeign调用服务请求头丢失Token
导致原因:
解决方案:
代码实现
@Configuration
@Slf4j
public class FeignConfig {
    @Value("${jwt.header}")
    private String tokenHeader;
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                log.info("进入feign拦截器...");
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();// 老请求
                String authorization = request.getHeader(tokenHeader);
                log.info(authorization);
                requestTemplate.header(tokenHeader, authorization);
            }
        };
    }
}
Feign传参对象数据丢失问题
Feigin不支持Key-value形式的请求体传参,所有在传递对象参数的时候需要将服务端的接口加上@RequstBody注解,Feign消费端也需要加上@RequstBody,但是会出现前端在直接访问服务器接口时,需要构建JSON串放在Body里传递过来。
Get请求又不支持Body。为了解决这个问题,这里记录解决方案。
1.如果不考虑前端直接调用接口和Feign调用接口不一致
服务端的接口加上@RequstBody注解,Feign消费端也需要加上@RequstBody。
2.升级springboot版本到2.1.x.使用Spring Cloud OpenFeign提供@SpringQueryMap注解
Feign里加上
    class AuditFeiginConfig {
        @Bean
        public Contract customerContract() {
            return new feign.Contract.Default();
        }
    }
完整Feign代码:
 
import feign.Contract;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import com.fasterxml.jackson.databind.JsonNode;
import com.galaplat.base.core.common.exception.BaseException;
import com.galaplat.product.center.databook.plugin.vos.AuditVO;
 
@FeignClient(name = "galaplat-product-center", fallback = AuditFeignHystrixService.class,configuration = IAuditFeign.AuditFeiginConfig.class)
public interface IAuditFeign {   
    @PostMapping("/XXX")
    JsonNode submit(@SpringQueryMap AuditVO auditVO) throws Exception;
    class AuditFeiginConfig {
        @Bean
        public Contract customerContract() {
            return new feign.Contract.Default();
        }
    }
}
这样服务端接口就不一定要加@RequstBody.
服务端接口代码
 //这里就可以不加@RequestBody,默认应该是@RequestParam
    @PostMapping("/XXX")
 public Object submit(AuditVO auditVO) throws Exception {
  return null;
 }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持无名。

教你用Java实现一个简单的代码生成器
maven项目打包上传到私有仓库

同类资源