我编写了一个小型 JAX-WS Web 服务,它在容器外部运行Endpoint.publish()
:
Endpoint endpoint = Endpoint.create(new MyServiceImpl());
endpoint.publish("http://localhost:4425/myService");
如果我的任何 Web 服务方法抛出异常,则端点不会正常关闭,并且该地址将继续使用,直到 Windows 最终释放它。这会导致经典错误:
com.sun.xml.internal.ws.server.ServerRtException:服务器运行时错误:java.net.BindException:地址已在使用中:绑定
我可以用 try/catch 包装所有的 Web 服务方法,但这似乎有点重复。我还尝试通过安装清理类Thread.setDefaultUncaughtExceptionHandler()
,但是当我的 Web 服务方法抛出异常时,这并没有被触发。
有没有比诉诸无数的 try/catch 块更优雅的方法来解决这个问题?
根据 Waldheinz 的回答,我尝试使用 Jetty 类来支持 JDK 默认值。代码可以编译,但执行时会立即终止publish
。当使用 JDK 类时,主线程将保持活动状态,直到我手动终止进程。有什么想法出了什么问题吗?我想知道是否某个地方发生了异常,但被吞没了,所以我看不到它。
Endpoint endpoint = Endpoint.create(new MyServiceImpl());
Server s = new Server(new InetSocketAddress(HOST, PORT));
ServerConnector connector = new ServerConnector(s);
connector.setReuseAddress(true);
s.setConnectors(new Connector[] { connector });
s.setHandler(new ContextHandlerCollection());
JettyHttpServer server = new JettyHttpServer(s, false);
JettyHttpContext context = (JettyHttpContext) server.createContext(PATH);
endpoint.publish(context);
端点的自定义线程池可能会有所帮助:
ThreadFactory factory = new ThreadFactory() {
@Override
public Thread newThread(Runnable target) {
final Thread thread = new Thread(target);
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
// put error handling code here
}
});
return thread;
}
};
ExecutorService executor = Executors.newCachedThreadPool(factory);
Endpoint endpoint = Endpoint.create(new MyServiceImpl());
endpoint.setExecutor(executor);
endpoint.publish("http://localhost:4425/myService");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)