SpringBoot怎么通过Feign调用传递Header中参数

寻技术 JAVA编程 2023年07月12日 124

本篇内容介绍了“SpringBoot怎么通过Feign调用传递Header中参数”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

【SpringBoot】通过Feign调用传递Header中参数

如何通过Feign传递Header参数

问题描述

我们在SpringCloud中使用Feign请求另一个服务的Api接口时,有将Header中参数传递下去的需求,如果不做特殊处理,就会将Header中的参数丢失。

解决方案

方案一:通过 @RequestHeader(name = "headerName") 来传递

例如:Feign定义如下

@FeignClient(name = "service-name")
public interface XXXFeignClient {
    @RequestMapping(value = "/user/getUserTicket", method = RequestMethod.GET)
    String getUserTicket(@RequestParam("id") String id);
}

假设在服务service-name中的/user/getUserTicket接口需要从Header中取Referer数据,那么我们可以将上面代码进行改造:

@FeignClient(name = "service-name")
public interface XXXFeignClient {
    @RequestMapping(value = "/user/getUserTicket", method = RequestMethod.GET)
    String getUserTicket(@RequestParam("id") String id, @RequestHeader(name = "Referer") String referer);
}

然后在调用的时候将referer参数传递进去即可,如

public String getTicketById(@RequestParam("id") String id, HttpServletRequest request) {
        String referer = request.getHeader("Referer");
        return xxxFeignClient.getUserTicket(id, referer);
    }

方案二:通过实现 RequestInterceptor 接口

首先,自定义实现RequestInterceptor接口的apply方法,如下

import org.springframework.stereotype.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
@Configuration
public class FeignConfiguration implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }
    }
}

然后将自定义的配置类配置到Feign中,就可以实现该Feign中接口Header参数的传递

@FeignClient(value = "service-name" ,configuration = FeignConfiguration.class)
    public interface XXXFeignClient {
    }
关闭

用微信“扫一扫”