使用resttemplate,有interceptor可以进行相应的拦截操作,那么使用feignclient呢,默认的实现是没有的,但是采取okhttp的实现来进行。

interceptor实例

@Component
public class OkHttpLoggingInterceptor implements Interceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpLoggingInterceptor.class);

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        //before , request.body()

        try {
            Response response = chain.proceed(request);
        //after
            return response;
        }catch (Exception e) {
            //log error
            throw e;
        }finally {
            //clean up 
        }
    }
}

feign配置

    @Bean
    @ConditionalOnBean(OkHttpLoggingInterceptor.class)
    public okhttp3.OkHttpClient okHttpClient(@Autowired
                                             OkHttpLoggingInterceptor okHttpLoggingInterceptor){
        okhttp3.OkHttpClient.Builder ClientBuilder = new okhttp3.OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS) //读取超时
                .connectTimeout(10, TimeUnit.SECONDS) //连接超时
                .writeTimeout(60, TimeUnit.SECONDS) //写入超时
                .connectionPool(new ConnectionPool(10 /*maxIdleConnections*/, 3, TimeUnit.MINUTES))
                .addInterceptor(okHttpLoggingInterceptor);
        return ClientBuilder.build();
    }

这样基本就大功告成了。


想获取最新内容,请关注微信公众号
图片描述


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...