单向服务
继续讨论之前,让我们了解一下处理单向服务(而非请求/响应服务)时涉及到的不同之处。
创建单向服务非常简单。此过程与创建请求/响应服务完全类似,至少不会实际返回任何内容。例如,可以为 CMSService
类创建 addArticle
操作,如图 29 中所示。
清单 29. CMSServiceclass 中的 addArticle 操作
... private Integer articleCount(String catId){ ... } public void addArticle(OMElement element) throws XMLStreamException{ element.build(); System.out.println(element); } } |
在 services.xml 文件中,将 addArticle
操作指定为“in only”操作,因此不会等待返回任何内容,但即使这样,也能看到会实际发生一些事项,会在命令行输出接收到的有效负载。您将在 Geronimo 窗口中看到此信息。
在实际应用程序中,此方法将从有效负载提取信息,并会实际添加到某种类型的数据库或其他存储库。
此服务的客户机也与请求/响应服务所使用的服务类似(请参见清单 30)。
清单 30. 创建客户机
import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.om.OMElement; import org.apache.axis2.SOAP.SOAPFactory; import org.apache.axis2.om.OMAbstractFactory; import org.apache.axis2.om.OMNamespace; public class AddArticleClient { private static EndpointReference targetEPR = new EndpointReference( "http://localhost:8080/axis2/services/CMSService"); private static OMElement getOMElement(){ SOAPFactory fac = OMAbstractFactory.getSOAP12Factory(); OMNamespace omNs = fac.createOMNamespace( "http://daily-moon.com", "cms"); OMElement method = fac.createOMElement("addArticle", omNs); OMElement category = fac.createOMElement("category", omNs); category.setText("classifieds"); OMElement subcategory = fac.createOMElement("subcategory", omNs); category.setText("wantads"); OMElement adtext = fac.createOMElement("article", omNs); adtext.setText("Do you have good head for numbers"+ " and a great deal of patience? Do you like"+ " to sit for hours sorting objects by their"+ " size? If so, then you could be the"+ " next goober counter in the world famous"+ " Murphy Brothers peanut factory. "+ " Willingness to dress up as our mascot"+ " helpful, but not required."); method.addChild(category); method.addChild(subcategory); method.addChild(adtext); return method; } public static void main(String[] args) { try { OMElement payload = AddArticleClient.getOMElement(); ServiceClient serviceClient = new ServiceClient(); Options options = new Options(); serviceClient.setOptions(options); options.setTo(targetEPR); serviceClient.fireAndForget(payload); } catch (AxisFault axisFault) { axisFault.printStackTrace(); } } } |
尽管有效负载不同,但正如您在 getOMElement()
方法中看到的,编程方面目前的唯一真正的更改是使用fireAndForget()
方法替代 sendReceive()
方法。此方法并不会返回响应。
如果运行此客户机,应该在 Geronimo 窗口中看到与图 5 中所示类似的输出。
图 5. 命令行输出
![命令行输出](https://i-blog.csdnimg.cn/blog_migrate/d699b28b3accce7980243fe1c0046965.png)