有没有办法终止CXF Web服务调用?

时间:2015-11-13 12:44:51

标签: java web-services cxf

我正在使用CXF来调用Web服务。它的使用方式与文档中描述的一样简单:

HelloService service = new HelloService();
Hello client = service.getHelloHttpPort();

String result = client.sayHi("Joe");

如果需要时间,我该如何终止此服务电话?

我发现只有一个相关的问题,但这并没有提供任何解决方案。

How to terminate CXF webservice call within Callable upon Future cancellation

1 个答案:

答案 0 :(得分:0)

我认为这更像是Web服务器的功能。例如,如果您使用Jetty来提供CXF内容,那么您可以将线程池​​设置为可以监视线程的内容。

ThreadPoolExecutor pool = new ThreadPoolExecutor(...);
ExecutorService svc = new ControlledExecutorService(pool);
server.setThreadPool(new org.eclipse.jetty.util.thread.ExecutorThreadPool(svc));

然后是自定义执行器服务(对不起,所有代码都直接在浏览器中输入。我在没有Java的iPad上。所以你可能需要稍作调整,但有用的部分应该在这里):

public class ControlledExecutorService implements ExecutorService {
    private ExecutorService es;

    public ControlledExecutorService(ExecutorService wrapped) {
        es = wrapped;
    }

    @Override
    public void execute(final Runnable command) {
        Future<Boolean> future = submit(new Callable< Boolean >() {
            public Boolean call() throws Exception {
                command.run();
                return true;
            }
        });

        // Do the proper monitoring of your Future and interrupt it
        // using Future.cancel(true) if you need to.
    }
}

请务必将true传递给cancel(),以便发送中断。

还要记住,就像任何线程一样,只是因为你发送了一个中断,这并不意味着它会遵守。你必须在你的线程中做一些工作,以确保他们表现得很好。值得注意的是,定期检查Thread.currentThread().isInterrupted()并正确处理InterruptedException以获取它并优雅地停止任务,而不是让异常将所有内容都搞砸。