springboot集成feign 拦截器Interceptor的使用

本文介绍了如何在SpringBoot中利用Feign的Interceptor接口实现日志记录和权限校验等通用业务逻辑。通过创建Interceptor实现类,注入到Spring容器中,即可在请求发送时触发自定义处理逻辑,例如日志打印。

feign中可以使用拦截器Interceptor实现一些通用的业务逻辑,比如记录日志,权限校验等。
feign提供了 feign.RequestInterceptor 接口,只需实现该接口,实现对应方法,并将实现类通过 @Component 交给spring容器管理,即可加上我们自己的通用处理逻辑。

下面看代码实现:

package com.wandou.springbootfeign.config;

import feign.MethodMetadata;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author liming
 * @date 2020/11/18
 * @description
 */

@Component
public class FeignInterceptor implements RequestInterceptor {

    private final Logger logger = Logger.getLogger(FeignInterceptor.class.getCanonicalName());


    /**
     * 本方法每个请求都会调用,可以通过RequestTemplate上的方法加入数据或处理逻辑。
     * Called for every request. Add data using methods on the supplied {@link RequestTemplate}.
     *
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        byte[] body = template.body();
        String url = template.url();
        String method = template.method();
        logger.info("通过feign请求接口, method: " + method + ", url: " + url + ", body: " + (body == null ? "" : new String(body)));
    }
}

当发送请求是会看到如下日志:

2020-11-20 11:48:02.940  INFO 28388 --- [ystrix-mouse-10] c.w.s.config.FeignInterceptor            : 通过feign请求接口, method: POST, url: /commodity/list, body: {}

这样来实现记录日志的通用逻辑。
如果还需要做其他处理,可以对 RequestTemplate 做相应处理来实现。


源码:https://github.com/wandou9527/spring-boot-feign

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大树91

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

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

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

打赏作者

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

抵扣说明:

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

余额充值