CXF client在并发下的线程安全问题 - 编程入门网
mcsis = new MessagingChannelServiceImplService(serviceWsdlUrl);
mcs = mcsis.getMessagingChannelServiceImplPort();
MessagingChannelService是cxf自动生成的,这个是@WebService,其他的业务代码都是调用它上面的业务方法来实现。由于serviceWsdlUrl不变,因此我们重用了一些东西,避免每次都初始化一次。看来问题出现在这里,试着将代码修改为threadlocal,让每个线程都初始化一次然后保存给自己使用。 修改后的客户端代码在之后的测试中,非常稳定,没有再出现上面的异常,问题算是解决了。 我对cxf不是很熟悉,找了一下也没有找到到底是那里造成的线程不安全,google了一下找到几个地方,但是似乎还不能完全说明问题。先列出来慢慢研究: 1) Are JAX-WS client proxies thread safe? 装载自这里:http://cxf.apache.org/faq.html#FAQ-AreJAXWSclientproxiesthreadsafe%253F Official JAX-WS answer: No. According to the JAX-WS spec, the client proxies are NOT thread safe. To write portable code, you should treat them as non-thread safe and synchronize access or use a pool of instances or similar. CXF answer: CXF proxies are thread safe for MANY use cases. The exceptions are: * Use of ((BindingProvider)proxy).getRequestContext() - per JAX-WS spec, the request context is PER INSTANCE. Thus, anything set there will affect requests on other threads. With CXF, you can do: ((BindingProvider)proxy).getRequestContext().put("thread.local.request.context", "true"); ((BindingProvider)proxy).getRequestContext().put("thread.local.request.context", "true"); and future calls to getRequestContext() will use a thread local request context. That allows the request context to be threadsafe. (Note: the response context is always thread local in CXF) * Settings on the conduit - if you use code or configuration to directly manipulate the conduit (like to set TLS settings or similar), those are not thread safe. The conduit is per-instance and thus those settings would be shared. * Session support - if you turn on sessions support (see jaxws spec), the session cookie is stored in the conduit. Thus, it would fall into the above rules on conduit settings and thus be shared across threads. For the conduit issues, you COULD install a new ConduitSelector that uses a thread local or similar. That''s a bit complex though. For most "simple" use cases, you can use CXF proxies on multiple threads. The above outlines the workarounds for the others. 2) cxf的wiki中谈到Client API中的Proxy-based API wiki 地址: http://cwiki.apache.org/CXF20DOC/jax-rs.html Limitations Proxy methods can not have @Context method parameters and subresource methods returning Objects can not be invoked - perhaps it is actually not too bad at all - please inject contexts as field or bean properties and have subresource methods returning typed classes : interfaces, abstract classes or concrete implementations. Proxies are currently not thread-safe. 3) thread safe issue caused by XMLOutputFactoryImpl 找到的一个cxf的bug,https://issues.apache.org/jira/browse/CXF-2229 Desc |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |