用MTOM在WCF和CXF之间传数据
用MTOM在WCF和CXF之间传数据
MTOM是一种机制,用来以原始字节形式传输包含SOAP消息的较大二进制附件,从而使所传输的消息较小。
如果不用MTOM我们也可以通过WebService传递二进制的文件, 我们先来看看不用MTOM的时候是什么样子的。
服务端是一个简单的WebService方法, 接受一个byte数组,计算其中的字符数并返回。
@WebServicepublic interface CounterService { int count(byte[] data);}
@Service@WebService(endpointInterface = "com.cccis.ws.CounterService")public class CounterServiceImpl implements CounterService { @Override public int count(byte[] data) { try { String text = GZipUtils.decompressText(data, "utf-8"); return text.length(); } catch (IOException e) { e.printStackTrace(); return -1; } }}
<bean id="countServiceImpl" /><jaxws:endpoint id="countService" implementor="#countServiceImpl" serviceName="countService" address="/countService" />
try{ var service = new ServiceReference1.CounterServiceClient(); var text = File.ReadAllText("c:\\words"); var memoryStream = new MemoryStream(); var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress); var rawData = Encoding.UTF8.GetBytes(text); gzipStream.Write(rawData, 0 , rawData.Length); gzipStream.Close(); var len = service.count(memoryStream.ToArray()); Console.WriteLine("lenght = {0}", len);}catch (Exception e){ Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace);}Console.Read();}
<?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <bindings> <basicHttpBinding> <binding name="countServiceSoapBinding" /> </basicHttpBinding> </bindings> <client> <endpoint address="http://192.168.2.3:8080/binder/services/countService" binding="basicHttpBinding" bindingConfiguration="countServiceSoapBinding" contract="ServiceReference1.CounterService" name="CounterServiceImplPort" /> </client> </system.serviceModel></configuration>
@WebServicepublic interface CounterService { int count(@XmlMimeType("application/octet-stream") DataHandler value);}
@Service@WebService(endpointInterface = "com.cccis.ws.CounterService")public class CounterServiceImpl implements CounterService { @Override public int count(DataHandler data) { try { String text = GZipUtils.decompressText(data.getInputStream(), "utf-8"); return text.length(); } catch (IOException e) { e.printStackTrace(); return -1; } }}
<jaxws:endpoint id="countService" implementor="#countServiceImpl" serviceName="countService" address="/countService"> <jaxws:properties> <entry key="mtom-enabled" value="true" /> </jaxws:properties> </jaxws:endpoint>
<?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <bindings> <customBinding> <binding name="countServiceSoapBinding"> <mtomMessageEncoding messageVersion="Soap11"></mtomMessageEncoding> <httpTransport/> </binding> </customBinding> </bindings> <client> <endpoint address="http://192.168.2.3:8080/binder/services/countService" binding="customBinding" bindingConfiguration="countServiceSoapBinding" contract="ServiceReference1.CounterService" name="CounterServiceImplPort" /> </client> </system.serviceModel></configuration>