2016-07-23 112 views
5

考虑OkHttp以下的初始化和改造:Okhttp忽略调度设置

public static SomeServiceRestInterface newRestService(String apiUrl) { 
      Retrofit retrofit = new Retrofit.Builder() 
        .baseUrl(apiUrl) 
        .client(createOkHttpClient()) 
        .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) 
        .addConverterFactory(createGsonConverter()) 
        .build(); 
      return retrofit.create(SomeServiceRestInterface.class); 
} 

private static OkHttpClient createOkHttpClient() { 
        Dispatcher dispatcher = new Dispatcher(); 
        dispatcher.setMaxRequestsPerHost(1); 
        dispatcher.setMaxRequests(1); 
        OkHttpClient.Builder builder = new OkHttpClient.Builder() 
           .dispatcher(dispatcher).build() 
} 

当测试REST调用,我注意到,Okhttp根本不兑现setMaxRequestsPerHost或setMaxRequests设置所有。以下是同时发送的3个请求的日志:

23/07 04:14:22.668 [RxIoScheduler-4] DEBUG - --> POST https://XXX/1 http/1.1 
23/07 04:14:22.668 [RxIoScheduler-4] DEBUG - Content-Length: 0 
23/07 04:14:22.668 [RxIoScheduler-4] DEBUG - --> END POST (0-byte body) 
23/07 04:14:22.672 [RxIoScheduler-7] DEBUG - --> POST https://XXX/2 http/1.1 
23/07 04:14:22.673 [RxIoScheduler-7] DEBUG - Content-Length: 0 
23/07 04:14:22.673 [RxIoScheduler-7] DEBUG - --> END POST (0-byte body) 
23/07 04:14:22.676 [RxIoScheduler-6] DEBUG - --> POST https://XXX/3 http/1.1 
23/07 04:14:22.677 [RxIoScheduler-6] DEBUG - Content-Length: 0 
23/07 04:14:22.677 [RxIoScheduler-6] DEBUG - --> END POST (0-byte body) 

其中XXX是相同的域,1/2/3是不同的路径。

我不知道为什么,但我认为这可能与在addCallAdapterFactory中设置的RxJava Scheduler有关。

这是一个错误?或者我错过了什么?

我使用的是okhttp 3.4.1,并且改进了2.1.0。

+0

您是否检查过您创建了多少个http客户端? –

回答

4

引述在这个问题上杰克沃顿:

的观察到的,改造的实施执行请求 同步依靠应用调度任何必然 限制。如果您需要OkHttp的调度程序的限制为 ,那么您必须编写一个自定义的CallAdapter for Observable ,它使用Call.enqueue而不是Call.execute。

我们目前还没有计划,以支持这一点,但很可能是建立在一个假设的OkHttp V4 改造V3可能使这个 默认的(尽管这是一个很长的路要走)。

如果您使用Retrofit的调用 并调用.execute(),或者甚至将OkHttp的调用与其.execute()一起使用,则会出现相同的行为。