我正在使用 Oracle Jersey Client
,并试图取消长期运行 get
或 put
手术。Client
构造为:
JacksonJsonProvider provider = new JacksonJsonProvider(new ObjectMapper());
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getSingletons().add(provider);
Client client = Client.create(clientConfig);
以下代码在工作线程上执行:
File bigZipFile = new File("/home/me/everything.zip");
WebResource resource = client.resource("https://putfileshere.com");
Builder builder = resource.getRequestBuilder();
builder.type("application/zip").put(bigZipFile); //This will take a while!
我想取消这个长期运行的
put
.当我尝试中断工作线程时,put
操作继续运行。据我所知, Jersey 客户端没有尝试检查 Thread.interrupted()
.使用
AsyncWebResource
时我看到相同的行为而不是 WebResource
并使用 Future.cancel(true)
在 Builder.put(..)
称呼。到目前为止,我想出的唯一解决方案是抛出
RuntimeException
在 ContainerListener :client.addFilter(new ConnectionListenerFilter(
new OnStartConnectionListener(){
public ContainerListener onStart(ClientRequest cr) {
return new ContainerListener(){
public void onSent(long delta, long bytes) {
//If the thread has been interrupted, stop the operation
if (Thread.interrupted()) {
throw new RuntimeException("Upload or Download canceled");
}
//Report progress otherwise
}
}...
我想知道是否有更好的解决方案(可能在创建
Client
时)可以在不使用 RuntimeException
的情况下正确处理可中断的 I/O。 .
最佳答案
I am wondering if there is a better solution (perhaps when creating the Client) that correctly handles interruptible I/O without using a RuntimeException.
是的,只有当代码正在监视中断或调用监视它的其他方法(例如
Thread.sleep(...)
)时,才能中断线程。从监听器中抛出异常听起来不错。我当然会创建您自己的
RuntimeException
类如 TimeoutRuntimeException
或其他东西,以便您可以专门捕获并处理它。另一件事是关闭正在写入的底层 IO 流,这将导致
IOException
但我对 Jersey 不熟悉,所以我不确定你是否可以访问连接。啊,这是一个想法。而不是把
File
,在 BufferedInputStream
上添加某种扩展怎么样?那是从 File
中读取的但也有超时。所以 Jersey 会从缓冲区读取,并且在某个时候它会抛出一个 IOException
如果超时到期。
关于java - 中断长时间运行的 Jersey 客户端操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23660327/