当前位置: 首页 > 知识库问答 >
问题:

在方法抛出异常后,重新分配客户端保持连接

咸浩初
2023-03-14

我目前正在使用TJWSEmBeddedJaxrsServer来帮助我进行我的RESTful应用编程接口测试(用RestEasy创建),它工作起来非常好。但是当任何被调用的方法抛出异常时,就会出现问题: Reastethy客户端变得“丢失”,并且仍然保持连接,不允许其他测试方法调用RESTful服务。即使您实例化了一个可以打开异常并在嵌入式服务器中使用它的提供程序,也会发生这种情况。

谁能帮帮我吗?

为了模拟这个问题,它实际上很容易:

  1. 下载Mark Paluch在中提供的示例https://github.com/mp911de/rest-api-test
  2. 将测试类更改为如下所示:

公共类InMemoryRestTest{

@Path("/myresource")
public static class MyResource {

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.APPLICATION_XML)
    public MyModel createMyModel(int number) throws Exception {
        // supose this is a Business exception
        throw new Exception("Test");
    }

}

public static MyResource sut = new MyResource();
public static InMemoryRestServer server;

@BeforeClass
public static void beforeClass() throws Exception {
    server = InMemoryRestServer.create(sut);
}

@AfterClass
public static void afterClass() throws Exception {
    server.close();
}

@Test
public void postSimpleBody() throws Exception {
    // This one throws the "Exception" exception and passes     
    Response response = server.newRequest("/myresource").request().buildPost(Entity.text("42")).invoke();
    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}

@Test
public void postAnother() throws Exception {
    // This one fails with "Invalid use of BasicClientConnManager: connection still allocated."
    Response response = server.newRequest("/myresource").request().buildPost(Entity.text("20")).invoke();
    assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}

}

瞧!当“postAnother()”的测试运行时,将发生以下错误:

javax.ws.rs.ProcessingException: Unable to invoke request
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:287)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:407)
    at biz.paluch.rest.test.InMemoryRestTest.postSimpleBody(InMemoryRestTest.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
    at org.apache.http.impl.conn.BasicClientConnectionManager.getConnection(BasicClientConnectionManager.java:162)
    at org.apache.http.impl.conn.BasicClientConnectionManager$1.getConnection(BasicClientConnectionManager.java:139)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:456)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:283)
    ... 27 more

共有3个答案

薛坚
2023-03-14

在JavaSE7及更高版本中,更干净的方法是使用try-with-resources。示例代码片段如下:

try(response = server.newRequest("...").request().buildPost(Entity.text("...")).invoke())
{ 
   /* response handling logic */ 
}
巫马善
2023-03-14

您需要配置ResteasyClientBuilder以使用连接池。按照以下方式修改InMemoryRestServer类的withDefaults()方法

//this.resteasyClient = new ResteasyrestEasyClientBuilder().build();
ResteasyrestEasyClientBuilder restEasyClientBuilder = new ResteasyrestEasyClientBuilder();
restEasyClientBuilder = restEasyClientBuilder.connectionPoolSize(20);
this.resteasyClient = restEasyClientBuilder.build();

这样,您的两个测试用例都应该无一例外地运行(但似乎都会抛出断言错误)

齐英朗
2023-03-14

默认的RestasyClientBuilder不使用连接池,这意味着您一次只能有一个并行连接。因此,您必须确保关闭响应(即response.close())才能释放(唯一的)连接。

请参见此处的响应实现:https://github.com/resteasy/Resteasy/blob/master/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientResponse.java

public void close()
   {
      if (isClosed()) return;
      try {
         isClosed = true;
         releaseConnection(); // <= HERE!
      }
      catch (Exception e) {
         throw new ProcessingException(e);
      }
   }

因此,以下内容应该可以解决您的问题:

@Test
public void postBody() throws Exception {          
    Response response = null;
    try {
        response = server.newRequest("...").request().buildPost(Entity.text("...")).invoke();           
    } finally {
        response.close();
    }   
}

祝好

伯纳德。

 类似资料:
  • 我需要多次调用服务(>50次)并聚合响应。因此,我决定使用,使用Async和CustomExecuter(它自己的线程池)来提高速度,而不是等待服务响应。 我在类路径上使用带有ApacheHTTP和Hystrix的feign客户机。我可以看到它有时是工作的,有时我得到例外,因为电路是开放的。

  • 问题内容: 我有一个关于Java中重新引发异常的非常简单的问题。 这是代码片段: 为什么我们需要在第一个版本中重新抛出,而第二个版本看起来更优雅?可能有什么好处,并且优先选择哪个版本? 问题答案: 你是对的。第二版更好。而且,第一个版本没有任何意义。除了异常的堆栈跟踪为“错误”之外,它的功能相同。 有“重新抛出”异常的原因如下: 如果您之前有事要做。 如果捕获一种类型的异常并抛出另一种类型的异常:

  • 我正在使用具有以下配置的Redisson连接到哨兵服务器:

  • 假设我想在收到特定异常时恢复某个值,否则返回失败的未来。我希望是这样的: 如果函数会抛出检查过的异常,我想在链式方法中处理它。我尝试过和,但都无法编译。是否为这种情况提供了任何解决方案?我知道接口是方法的参数,它不会抛出任何异常——在这种情况下,我只想返回已经失败的未来。我想找到使用Java8的解决方案。

  • 我使用hibernate持久化方法得到了一些奇怪的结果。下面是解释。 1) 用户服务简单 2) 用户道 3) JSMListener 现在,当我传递重复的电子邮件id时,我的userDao方法应该抛出异常,然后我的下一步* * message sender . send user message(queue,user dto);**不应该叫。但当我传递重复的电子邮件id时,UserDaoImpl抛

  • 有什么特殊的配置需要保持TwilioiOS客户端在后台活动吗?我已经启用了“VoIP”和“音频”权限,但是我注意到我的应用在后台大约10分钟后就退出了。请注意,我已经禁用了“TCDevice”播放的声音,并且还对AVAudio会话配置进行了一些更改。