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

6094

被折叠的 条评论
为什么被折叠?



