【发布时间】:2012-07-11 08:49:12
【问题描述】:
我正在使用 cxf-codegen-plugin 开发 Web 服务客户端,它正在为客户端部分生成类 MyService extends Service。
我现在的问题是:当我创建客户端时,我的MyService 对象是否应该在每次我想发送请求或保留它并且每次创建端口时创建?或者我可以保留端口吗?什么是做客户的最佳方式?
谢谢
【问题讨论】:
标签: java web-services jax-ws cxf
我正在使用 cxf-codegen-plugin 开发 Web 服务客户端,它正在为客户端部分生成类 MyService extends Service。
我现在的问题是:当我创建客户端时,我的MyService 对象是否应该在每次我想发送请求或保留它并且每次创建端口时创建?或者我可以保留端口吗?什么是做客户的最佳方式?
谢谢
【问题讨论】:
标签: java web-services jax-ws cxf
保留端口绝对是性能最佳的选择,但请记住线程安全方面:
http://cxf.apache.org/faq.html#FAQ-AreJAXWSclientproxiesthreadsafe%3F
【讨论】:
每次发送请求时创建Service 类将是非常低效的方式。创建 Web 服务客户端的正确方法是在第一次应用程序启动时。例如我从 Web 应用程序调用 Web 服务并使用 ServletContextListener 来初始化 Web 服务。 CXF Web 服务客户端可以这样创建:
private SecurityService proxy;
/**
* Security wrapper constructor.
*
* @throws SystemException if error occurs
*/
public SecurityWrapper()
throws SystemException {
try {
final String username = getBundle().getString("wswrappers.security.username");
final String password = getBundle().getString("wswrappers.security.password");
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
username,
password.toCharArray());
}
});
URL url = new URL(getBundle().getString("wswrappers.security.url"));
QName qname = new QName("http://hltech.lt/ws/security", "Security");
Service service = Service.create(url, qname);
proxy = service.getPort(SecurityService.class);
Map<String, Object> requestContext = ((BindingProvider) proxy).getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url.toString());
requestContext.put(BindingProvider.USERNAME_PROPERTY, username);
requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Timeout", Collections.singletonList(getBundle().getString("wswrappers.security.timeout")));
requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
} catch (Exception e) {
LOGGER.error("Error occurred in security web service client initialization", e);
throw new SystemException("Error occurred in security web service client initialization", e);
}
}
在应用程序启动时,我创建这个类的实例并将其设置为应用程序上下文。还有一种使用spring创建客户端的好方法。看这里:http://cxf.apache.org/docs/writing-a-service-with-spring.html
希望这会有所帮助。
【讨论】: