首頁 >Java >java教程 >SpringBoot怎麼透過Feign呼叫傳遞Header中參數

SpringBoot怎麼透過Feign呼叫傳遞Header中參數

PHPz
PHPz轉載
2023-05-16 20:38:072604瀏覽

【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刪除