2012-07-11 87 views
3


我正在开发带有cxf codegen的web服务客户端,它为客户端部分生成MyService extends Service类。
我现在的问题是当我创建客户端时,应该是每次我想要发送请求时创建的MyService对象,还是每次创建端口?或者我还可以保留Port吗?什么是让客户最好的方式?Web服务客户端,我应该保留服务或端口实例吗?

感谢

回答

0

要创建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

希望这会有所帮助。

+0

使你保持代理(端口)的初始化WS – JIV 2012-07-16 13:09:02