java - 中断长时间运行的 Jersey 客户端操作

标签 java multithreading jersey httpconnection cancellation

我正在使用 Oracle Jersey Client ,并试图取消长期运行 getput手术。
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(..)称呼。

到目前为止,我想出的唯一解决方案是抛出 RuntimeExceptionContainerListener :
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/

相关文章:

java - 将 XML 字符串转换为 Jersey XML 输出中的有效 XML

rest - 使用 Jersey 的 REST with Java (JAX-RS) 中的欢迎页面

java - 所有 Activity 中的语言都不会改变

java - Java中如何检查数据库凭据是否正确?

multithreading - go 语言 web 框架设计线程明智

c# - 处理 ErrorDataReceived 时出现 NullReferenceException - 终止线程

java - 在 Weblogic 12.1.1 上使用 Jersey 2.x Web 服务

java - 我可以通过mysql触发器执行mysql之外的任何程序吗?

java - 当我尝试连接到 Mysql 时检测到 JSONException 时,如何修复错误?

objective-c - 当 Cocoa 应用程序中的主线程被阻塞时,UI 不会更新