如何在@Stateless bean中设置@WebMethod的超时值?

时间:2013-02-19 02:47:04

标签: java java-ee timeout stateless

我试图弄清楚是否可以在@Stateless bean中设置web方法的超时值。或者即使有可能。我搜索了很多,发现与这个问题无关。

示例:

@WebService
@Stateless
public class Test {

    @WebMethod
    @WebResult(name = "hello")
    public String sayHello(){
        return "Hello world";
    }
}

提前感谢您的任何答案。

1 个答案:

答案 0 :(得分:3)

所以在搜索和学习之后我通过执行以下操作解决了这个问题:我创建了一个包含@Asynchronous方法的无状态Bean:

@Asynchronous
public Future<String> sayHelloAsync() 
{
     //do something time consuming ...
     return new AsyncResult<String>("Hello world");
}

然后在第二个bean中将其方法暴露为Web服务,我已经完成了以下操作:

@WebService
@Stateless
public class Test {

     @EJB
     FirstBean myFirstBean;//first bean containing the Async method.

    /**
     * Can be used in futher methods to follow
     * the running web service method
     */
    private Future<String> myAsyncResult;

    @WebMethod
    @WebResult(name = "hello")
    public String sayHello(@WebParam(name = "timeout_in_seconds") long timeout)
    {
        myAsyncResult = myFirstBean.sayHelloAsync();
        String myResult = "Service is still running";
        if(timeout>0)
        {
            try {
                myResult= myAsyncResult.get(timeout, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                myResult="InterruptedException occured";
            } catch (ExecutionException e) {
                myResult="ExecutionException occured";
            } catch (TimeoutException e) {
                myResult="The timeout value "+timeout+" was reached."+ 
                                 " The Service is still running.";
            }
        }
        return myResult;
    }
}

如果设置了超时,则客户端将等待这段时间,直到达到。这个过程仍然需要在我的案例中运行。我希望它能帮助别人。