feignclient的拦截

使用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();
    }

这样基本就大功告成了。


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

qrcode_for_gh_121b87c80448_258.jpg

你可能感兴趣的:(feignclient的拦截)