Feign拦截器-Feign

概述

Feign支持请求拦截器,在发送请求前,对发送的模板进行操作,例如设置请求头等属性。
在使用feign做服务间调用的时候,如何修改请求的头部或编码信息呢,可以通过实现RequestInterceptor接口的apply方法,feign在发送请求之前都会调用该接口的apply方法,所以我们也可以通过实现该接口来记录请求发出去的时间点。

自定义请求拦截器

  1. 实现feign.RequestInterceptor接口;
  2. 实现方法apply(RequestTemplate template);
  3. 设置header属性:template.header(name,values);
  4. 设置param属性:template.query(name,values);

自定义拦截器示例

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Created by xiaoxian on 2021/1/27.
 * @version v0.1.0
 * @see <font color="#0000FF">house-parent</font>
 */
public class FeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if (request != null) {
                //设置header属性:requestTemplate.header(name, values);
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        requestTemplate.header(name, values);
                    }
                }
                
                //设置param属性:requestTemplate.query(name, values);
                Enumeration<String> paramNames = request.getParameterNames();
                if (paramNames != null) {
                    Map map=new HashMap();
                    while (paramNames.hasMoreElements()) {
                        String name = paramNames.nextElement();
                        String values = request.getParameter(name);
                        requestTemplate.query(name, values);
                    }
                }
            }
        }
    }
}

Feign中已实现了RequestInterceptor接口的拦截器

RequestInterceptor接口定义了apply方法,其参数为RequestTemplate,它有一个抽象类为BaseRequestInterceptor,
还有几个实现类分别为:BasicAuthRequestInterceptor、FeignAcceptGzipEncodingInterceptor、FeignContentGzipEncodingInterceptor。

BasicAuthRequestInterceptor

BasicAuthRequestInterceptor实现了RequestInterceptor接口,其apply方法往RequestTemplate添加名为Authorization的header

BaseRequestInterceptor

BaseRequestInterceptor定义了addHeader方法,往requestTemplate添加非重名的header

FeignAcceptGzipEncodingInterceptor

FeignAcceptGzipEncodingInterceptor继承了BaseRequestInterceptor,它的apply方法往RequestTemplate添加了名为Accept-Encoding,值为gzip,deflate的header

FeignContentGzipEncodingInterceptor

FeignContentGzipEncodingInterceptor继承了BaseRequestInterceptor,其apply方法先判断是否需要compression,即mimeType是否符合要求以及content大小是否超出阈值,需要compress的话则添加名为Content-Encoding,值为gzip,deflate的header

小结

  • RequestInterceptor接口定义了apply方法,其参数为RequestTemplate;它有一个抽象类为BaseRequestInterceptor,还有几个实现类分别为BasicAuthRequestInterceptor、FeignAcceptGzipEncodingInterceptor、FeignContentGzipEncodingInterceptor
  • BasicAuthRequestInterceptor实现了RequestInterceptor接口,其apply方法往RequestTemplate添加名为Authorization的header
  • BaseRequestInterceptor定义了addHeader方法,往requestTemplate添加非重名的header;FeignAcceptGzipEncodingInterceptor继承了BaseRequestInterceptor,它的apply方法往RequestTemplate添加了名为Accept-Encoding,值为gzip,deflate的header;FeignContentGzipEncodingInterceptor继承了BaseRequestInterceptor,其apply方法先判断是否需要compression,即mimeType是否符合要求以及content大小是否超出阈值,需要compress的话则添加名为Content-Encoding,值为gzip,deflate的header

参考

feign拦截器–RequestInterceptor
SpringBoot——》Feign的拦截器RequestInterceptor

### 如何在Feign拦截器中处理响应Token 为了实现通过Feign拦截器处理响应中的Token,通常需要自定义`RequestInterceptor`以及监听并解析HTTP响应头。以下是具体方法: #### 自定义Feign拦截器 可以通过继承`RequestInterceptor`类来自定义请求拦截逻辑,在其中设置必要的请求头信息。 ```java import feign.RequestInterceptor; import feign.RequestTemplate; public class CustomFeignInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate template) { // 设置请求头参数,比如 Access-Token 或其他认证信息 String accessToken = "your_access_token"; // 这里可以从上下文中动态获取 Token template.header("Authorization", "Bearer " + accessToken); } } ``` 上述代码展示了如何向每个Feign请求添加特定的Header字段[^3]。 #### 配置Feign客户端以支持拦截器 为了让Feign客户端能够应用自定义的拦截器,需将其注册到Spring容器中。 ```yaml feign: client: config: default: loggerLevel: FULL # 开启完整的日志记录以便调试 ``` 以上YAML配置文件片段用于启用详细的日志输出,便于观察Http请求的具体情况[^2]。 #### 解析响应头部提取Token 虽然Feign本身不提供直接的方式去操作响应体之外的数据(如Headers),但是可以借助装饰模式或者AOP技术来捕获返回值前后的状态变化。下面是一个简单的例子展示如果捕捉到Response Headers进而保存新的Session Tokens: ```java import feign.Response; import org.springframework.stereotype.Component; @Component public class ResponseHandler { public void handle(Response response){ // 获取所有的headers Map<String, Collection<String>> headers = response.headers(); // 查找是否有新产生的token if(headers.containsKey("New-Authorization")){ List<String> tokens = headers.get("New-Authorization"); if(!tokens.isEmpty()){ String newAccessToken = tokens.iterator().next(); // 更新本地缓存或者其他存储位置的新token值 updateLocalCache(newAccessToken); } } } private void updateLocalCache(String newAccessToken){ System.out.println("Updated access token to "+newAccessToken); } } ``` 此部分代码说明了当接收到服务器回应时,怎样检查是否存在更新版的身份验证令牌,并相应地刷新应用程序内部维护的状态副本[^1]。 #### 整合进业务流程 最后一步是要确保每次完成远程调用之后都会触发这个处理器函数执行。这可能涉及到修改现有的服务层架构设计或者是引入额外的技术手段像切面编程(AOP)等。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

融极

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值