首页  >  文章  >  Java  >  SpringBoot怎么通过Feign调用传递Header中参数

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

PHPz
PHPz转载
2023-05-16 20:38:072540浏览

【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 {
    }

以上是SpringBoot怎么通过Feign调用传递Header中参数的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:yisu.com。如有侵权,请联系admin@php.cn删除