Interception by feignclient

  springcloud

Order

With resttemplate, there is an interceptor that can perform corresponding interception operations. With feignclient, the default implementation is not available, but the implementation of okhttp is adopted.

Interceptor instance

@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 configuration

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

In this way, we are almost done.


For the latest content, please pay attention to WeChat public number
图片描述