尝试重新启动时 OkHttp WebSocket RejectedExecutionException

Kun*_*Lun 6 java websocket okhttp

我有这样的客户:

OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .pingInterval(Duration.ofMinutes(3))
            .readTimeout(Duration.ofMillis(0))
            .build();
Run Code Online (Sandbox Code Playgroud)

这个方法用于启动和停止:

private WebSocket webSocket = null;
private MyListener wsListener = null;

private void start(){

    if(webSocket != null){ return; }

    wsListener = new MyListener();

    Request request = new Request.Builder()
        .url("wss://stream.binance.com:9443/ws")
        .build();

    webSocketBinance = okHttpClient.newWebSocket(request, wsListener); //here triggers error

}

private void stop(){

    if(webSocket == null){ return; }

    webSocket.close(1000, "{\"reason\": \"With love\"}");
    webSocket= null;

    okHttpClient.dispatcher().executorService().shutdown();
    okHttpClient.connectionPool().evictAll();

    wsListener = null;

}
Run Code Online (Sandbox Code Playgroud)

有时我想像这样重新启动连接:

start();

Thread.sleep(10_000);

//restart connection
stop();
start(); //here triggers the error

Run Code Online (Sandbox Code Playgroud)

但在start()我得到这个错误:

java.io.InterruptedIOException: executor rejected
    at okhttp3.internal.connection.RealCall$AsyncCall.executeOn(RealCall.kt:501)
    at okhttp3.Dispatcher.promoteAndExecute(Dispatcher.kt:184)
    at okhttp3.Dispatcher.enqueue$okhttp(Dispatcher.kt:125)
    at okhttp3.internal.connection.RealCall.enqueue(RealCall.kt:164)
    at okhttp3.internal.ws.RealWebSocket.connect(RealWebSocket.kt:165)
    at okhttp3.OkHttpClient.newWebSocket(OkHttpClient.kt:281)
    at foo.Foo.start(...)

Caused by: 
java.util.concurrent.RejectedExecutionException: 
    Task okhttp3.internal.connection.RealCall$AsyncCall@2aceadd4 rejected from 
    java.util.concurrent.ThreadPoolExecutor@24aed80c
    [Shutting down, pool size = 1, active threads = 1, queued tasks = 0, completed tasks = 0]
    
at java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2080)
    
at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:832)
    
at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1365)
    
at okhttp3.internal.connection.RealCall$AsyncCall.executeOn(RealCall.kt:498)
    
... 8 more

Run Code Online (Sandbox Code Playgroud)

Kun*_*Lun 2

我的解决方案是每次我想重新启动时创建一个新的OkHttpClientWebSocket