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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐