【问题标题】:How to set the connection and read timeout with Jersey 2.x?如何使用 Jersey 2.x 设置连接和读取超时?
【发布时间】:2013-11-01 19:39:34
【问题描述】:

在球衣 1 中,我们在 com.sun.jersey.api.client.Client 类中有一个函数 setConnectTimeout

在球衣 2 中,javax.ws.rs.client.Client 类用于缺少此功能的地方。

jersey 2.x中如何设置连接超时和读取超时?

【问题讨论】:

    标签: java jersey


    【解决方案1】:

    从球衣2.26(使用JAX-RS 2.1)开始有新的方法:

    ClientBuilder builder = ClientBuilder.newBuilder()
            .connectTimeout(5000, TimeUnit.MILLISECONDS)
            .readTimeout(5000, TimeUnit.MILLISECONDS);
            //some more calls if necesary, e.g.
            //.register(LoggingFilter.class);
                
            Client restClient = builder.build();
    

    【讨论】:

      【解决方案2】:

      您还可以为每个请求指定超时时间:

      public static void main(String[] args) {
          Client client = ClientBuilder.newClient();
          WebTarget target = client.target("http://1.2.3.4:8080");
      
          // default timeout value for all requests
          client.property(ClientProperties.CONNECT_TIMEOUT, 1000);
          client.property(ClientProperties.READ_TIMEOUT,    1000);
      
          try {
              Invocation.Builder request = target.request();
      
              // overriden timeout value for this request
              request.property(ClientProperties.CONNECT_TIMEOUT, 500);
              request.property(ClientProperties.READ_TIMEOUT, 500);
      
              String responseMsg = request.get(String.class);
              System.out.println("responseMsg: " + responseMsg);
          } catch (ProcessingException pe) {
              pe.printStackTrace();
          }
      }
      

      【讨论】:

      • 我不确定,但我认为您需要像这样将客户端重新分配回自身:client = client.property(...),因为属性方法返回更新的可配置实例。与request 相同。
      【解决方案3】:

      下面的代码在 Jersey 2.3.1 中适用于我(在此处找到灵感:https://stackoverflow.com/a/19541931/1617124

      public static void main(String[] args) {
          Client client = ClientBuilder.newClient();
      
          client.property(ClientProperties.CONNECT_TIMEOUT, 1000);
          client.property(ClientProperties.READ_TIMEOUT,    1000);
      
          WebTarget target = client.target("http://1.2.3.4:8080");
      
          try {
              String responseMsg = target.path("application.wadl").request().get(String.class);
              System.out.println("responseMsg: " + responseMsg);
          } catch (ProcessingException pe) {
              pe.printStackTrace();
          }
      }
      

      【讨论】:

      • 我怀疑这行不通。 .property(...) 返回一个客户端实例(构建器模式)。调用 .target() 时不会使用这些设置。
      • 其实可以的。构建器模式并没有说应该创建另一个实例。看源码就知道了,返回值就是实际的客户端(只是为了方便我们后续调用)。
      • 只是想知道如果超时会发生什么,我们会收到网关超时(504)还是会抛出异常?
      • @HardikPatel 如果连接尝试超时,它将引发异常。 “网关超时 504”来自网关,通过连接,因此只有在连接成功时才会发生。
      猜你喜欢
      • 2016-03-14
      • 2015-09-16
      • 2011-12-05
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      • 2017-07-08
      相关资源
      最近更新 更多