java - RestEasy异步请求空指针异常

标签 java asynchronous jax-rs resteasy wildfly-8

我在 Resteasy 工作,我必须向服务器发出异步请求。真正的目的是,我将提交一个表单,该表单将转换为 .xlsx 文件,至少需要 10 秒才能完成。所以异步请求是这里最好的方式。我遵循了以下链接中的程序。

https://docs.jboss.org/resteasy/docs/3.0.9.Final/userguide/html_single/#Asynchronous_HTTP_Request_Processing

我正在像这样发出 ajax 请求。

$.ajax({
    url : 'rest/parentPath/childPath',
    type : 'GET',
    success : function(data, status, xhr) {
        console.log(xhr.getResponseHeader('Location'));
    },
    failure : function(data) {
        console.log(data);
    },
    error : function(error,status) {

    }
});

父类.java

import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;

@Component
@Path("/parentPath")
public class ParentClass {
    @GET
    @Path("childPath")
    @Produces("text/plain")
    public void asyncFunction(@Suspended final AsyncResponse response){
        Thread t = new Thread() {
            @Override
            public void run()
            {
                try
                {
                    Response jaxrs = Response.ok("basic").type(MediaType.TEXT_PLAIN).build();         
                    System.out.println("entered======================= =================================================");
                    response.resume(jaxrs);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
}

如果我只是发出一个 ajax 请求,它会给我 503 服务不可用错误 但我确实执行了我的异步任务,我可以通过在 wildfly 日志中看到我的系统输出来确认。但这不是异步应该如何完成的方式。我必须能够在第二个请求中看到我的异步任务的响应。我遵循了此链接中的程序。

https://docs.jboss.org/resteasy/docs/3.0.9.Final/userguide/html_single/#async_job

如果我将 ?asynch=true 放在请求 url 中,我会立即收到 202 Accepted 的响应,其中包含异步作业的位置作为响应。但它甚至没有进入 try 语句。这样wildfly终端就报错了。

19:11:41,733 WARN  [org.jboss.resteasy.core.ExceptionHandler] (pool-4-thread-1) Failed executing GET /parentPath/childPath: org.jboss.resteasy.spi.BadRequestExcept
ion: Failed processing arguments of org.jboss.resteasy.spi.metadata.ResourceMethod@44d4407c
        at org.jboss.resteasy.core.MethodInjectorImpl.injectArguments(MethodInjectorImpl.java:104) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:112) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:296) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:250) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:237) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:356) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.AsynchronousDispatcher.invokeSuper(AsynchronousDispatcher.java:237) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.AsynchronousDispatcher$1.call(AsynchronousDispatcher.java:278) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.AsynchronousDispatcher$1.call(AsynchronousDispatcher.java:269) [resteasy-jaxrs-3.0.10.Final.jar:]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [rt.jar:1.8.0_25]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [rt.jar:1.8.0_25]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [rt.jar:1.8.0_25]
        at java.lang.Thread.run(Thread.java:745) [rt.jar:1.8.0_25]
Caused by: java.lang.NullPointerException
        at org.jboss.resteasy.core.ResourceMethodInvoker.initializeAsync(ResourceMethodInvoker.java:374) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.AsynchronousResponseInjector.inject(AsynchronousResponseInjector.java:43) [resteasy-jaxrs-3.0.10.Final.jar:]
        at org.jboss.resteasy.core.MethodInjectorImpl.injectArguments(MethodInjectorImpl.java:89) [resteasy-jaxrs-3.0.10.Final.jar:]
        ... 12 more

如果我再次使用 asynch=true 发出相同的请求,它会显示相同的错误,但使用 (pool-4-thread-2) 而不是 (pool-4-thread-1)

这意味着异常不是发生在服务器端,而是发生在运行时层。因为我的代码中发生的任何异常都会出现在日志文件中,但不会出现在 wildfly 终端中。我将发布 web.xml、WebConfig.java、build.gradle 文件。我只是在复制在 jboss 文档中完成的同样的事情,但我无法弄清楚为什么这个异常发生在 wildfly 层。

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

    <display-name>Web Application</display-name>

    <distributable />

    <listener>
        <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>

    <listener>
        <listener-class>org.jboss.resteasy.plugins.spring.SpringContextLoaderListener</listener-class>
    </listener>

    <!-- Context Configuration locations for Spring XML files -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:/applicationContext-resources.xml
            classpath:/applicationContext-dao.xml
            classpath:/applicationContext-service.xml
            classpath*:/applicationContext.xml
            /WEB-INF/applicationContext*.xml
        </param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.async.job.service.enabled</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.async.job.service.max.job.results</param-name>
        <param-value>100</param-value>
    </context-param>

    <!-- Maximum wait time on a job when a client is querying for it -->
    <context-param>
        <param-name>resteasy.async.job.service.max.wait</param-name>
        <param-value>300000</param-value>
    </context-param>

    <!-- Thread pool size of background threads that run the job -->
    <context-param>
        <param-name>resteasy.async.job.service.thread.pool.size</param-name>
        <param-value>100</param-value>
    </context-param>

    <!-- Set the base path for the Job uris -->
    <context-param>
        <param-name>resteasy.async.job.service.base.path</param-name>
        <param-value>/asynch/jobs</param-value>
    </context-param>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.mypackage.service.WebConfig</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>login.html</welcome-file>
    </welcome-file-list>

</web-app>

WebConfig.java

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.core.Application;

public class WebConfig extends Application {

    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> empty = new HashSet<Class<?>>();

    public WebConfig() {
        // ADD YOUR RESTFUL RESOURCES HERE
        this.singletons.add(new SignupService());
        this.singletons.add(new UserService());
        this.singletons.add(new ParentClass());
    }

    public Set<Class<?>> getClasses()
    {
        return this.empty;
    }

    public Set<Object> getSingletons()
    {
        return this.singletons;
    }

}

构建.gradle

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
apply plugin: 'eclipse'

// Uses JDK 8
sourceCompatibility = 1.8
targetCompatibility = 1.8

// 1. Get dependencies from Maven local repository
// 2. Get dependencies from Maven central repository
repositories {
    mavenLocal()
    mavenCentral()
    maven  {
        url "http://repo1.maven.org/maven2"
    }
}

configurations {
    provided
}
  sourceSets {
    main { compileClasspath += configurations.provided }
}

//Project dependencies
dependencies {

    //Spring framework core
    compile 'org.springframework:spring-web:4.1.4.RELEASE'
    compile 'org.springframework:spring-core:4.1.4.RELEASE'
    compile 'org.springframework:spring-context:4.1.4.RELEASE'
    compile 'org.springframework:spring-context-support:4.1.4.RELEASE'
    compile 'org.springframework:spring-orm:4.1.4.RELEASE'

    compile 'org.springframework.security:spring-security-core:4.0.0.RELEASE'

    //MySQL database driver
    //compile 'mysql:mysql-connector-java:5.1.34'
    compile 'com.oracle:ojdbc6:11.2.0.1.0'


    //Hibernate framework 
    compile 'org.hibernate:hibernate-core:4.3.8.Final'
    compile 'commons-dbcp:commons-dbcp:1.2.2'

    //Servlet API
    compile 'javax.servlet:servlet-api:2.5'

    //Base-64 Apache commons
    compile 'commons-codec:commons-codec:1.10'

    //log4j
    compile 'log4j:log4j:1.2.17'
    compile 'org.slf4j:slf4j-simple:1.7.10'

    //XmlBeans Equity Valuation
    compile 'org.apache.xmlbeans:xmlbeans:2.6.0'

    //Poi Equity Valuation
    compile 'org.apache.poi:poi:3.10.1'

    //Poi ooxml Equity Valuation
    compile 'org.apache.poi:poi-ooxml:3.10.1'

    //Poi ooxml Schemas Equity Valuation
    compile 'org.apache.poi:poi-ooxml-schemas:3.10.1'

    //Jacob Equity Valuation
    compile 'jacob:jacob:1.18-M2'

    //Google gson
    compile 'com.google.code.gson:gson:2.3.1'

    provided 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final'

    provided 'org.jboss.resteasy:resteasy-spring:3.0.11.Final'

}

最佳答案

试图在评论中添加但字数限制。
我现在可以做异步工作了。我发现使用 AsynchResponseSuspended 注释会导致此异常。这不是异步作业处理所必需的。
你的空指针的原因是两者混淆了。

有两个异步的东西,文档真的把它们混在一起了
1. 异步响应:使用 Suspended 和 AsynchResponse 将释放接收请求的服务器线程,工作将由创建的新线程完成。但是客户端会等待响应。直到您的新线程完成并将其发回。为此,无需对 web.xml 进行任何更改。


2. Asynchronous Job processing:在这里,您将 web.xml 中的 resteasy.async.job.service.enabled 设置为 true 以及任何其他可选的参数(如果需要)。不需要对 API 进行其他更改。我的方法是
@POST @Path("/ hell 世界") 公共(public)响应 getHelloWorld() { log.info("API 被调用"); longLiftingJob(); log.info("API调用完成"); 返回 Response.status(200).entity("Hello World").build(); }

使用 web.xml 中的 true 参数,框架将调用您调用一个新线程(简单地说),并在 202 响应中返回相同的作业 ID。作为位置 header 作为
位置 → http://127.0.0.1:8080/myrest/asynch/jobs/1432015827488-1

客户端在上面的 url 上执行 GET/POST,并在 API 完成后获得 API 返回的响应。但实际的客户端永远不会等待如此异步的工作。

关于java - RestEasy异步请求空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29563475/

相关文章:

c# - 同时多线程和异步

jakarta-ee - Jersey:区分 session 超时和未授权

javascript - Pusher:如何获取 Pusher 中的私有(private) channel 订阅数?

jax-rs - 如何使用Jersey(JAX-RS 2.0)客户端为内容编码启用gzip压缩?

java - 通过SSL通过Cajo连接时出现javax.net.ssl.SSLHandshakeException

java - Java 中的 StackOverflow 异常

java - 如何从 .jar 文件引用 .dll

java - 注入(inject) Autowiring 的依赖项失败;无法 Autowiring 字段

java - 异步加载 JButton 图标

c# - CsvHelper - 异步读取流