RestEasy ContainerRequestContext.abortWith在客户端中产生java.io.IOException

时间:2018-07-29 09:43:11

标签: java resteasy

我正在使用RESTEasy开发简单的REST Api。这是我正在使用的依赖项

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.6.0.Final</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-multipart-provider</artifactId>
    <version>3.6.0.Final</version>
</dependency> 

我有一个简单的过滤器,目的是如果服务器已经在处理N个此类请求,则中止传入的请求。需要明确的是,该过滤器仅应用于我们感兴趣的资源,并且可以正常工作。

@NamedFilter
public class MyCustomFilter implements ContainerRequestFilter, ContainerResponseFilter {

private static final Object lock = new Object();
private static int counter  = 0;

private static final int MAX_REQUESTS = 10;

@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
    boolean canProcess = false;
    synchronized (lock) {
        if (counter < MAX_REQUESTS) {
            counter += 1;
            canProcess = true;
        }
        if (!canProcess) {
            // The same behaviour
            // throw new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE);
            containerRequestContext.abortWith(
                    Response.
                            status(503).
                            entity("We cannot process your request now. Try again later").
                            build());
        }
    }
}

@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
    synchronized (lock) {
        if (containerResponseContext.getStatus() != 503) {
            counter --;
        }
    }
}

}

到目前为止,一切都很好。我正在使用curl发送请求,一切都很好。这是达到限制时的结果。

HTTP/1.1 100 

HTTP/1.1 503 
Content-Type: application/octet-stream
Content-Length: 38
Date: Sun, 29 Jul 2018 09:13:28 GMT
Connection: close

We cannot process your request now. Try again later

但是当我从curl转移到java时,挫败感降临了。如果未达到请求限制,则一切正常。但是当无法处理请求而不是状态503时,我收到java.io.IOException:写入服务器时出错

java.io.IOException: Error writing to server
    at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:665)
    at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:677)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1533)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1440)
    at Main.uploadPOJO(Main.java:135)
    at Main.main(Main.java:49)

正如我说的,如果未达到限制,则Java客户端可以正常工作,因此请假定代码没有问题。如有需要,我会在稍后发布。我还尝试了Appche HTTPClient并获得了相同的结果,但有不同的异常

java.net.SocketException: Broken pipe
    at java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
    at java.net.SocketOutputStream.write(SocketOutputStream.java:153)

最后是我的问题:为什么curl能够处理这种情况而Java无法处理?最重要的是,如何在Java中获得正确的状态?

谢谢。

0 个答案:

没有答案