作者:Dflying Chen (http://dflying.cnblogs.com/)
对于一些复杂的,需要较长时间完成,并且对实时性要求不是很高的服务,选择Cache往往是一个有效的提高效率的方法。.NET的Web Service实现充分考虑了对Cache的需求,您只需要简单的设定即可启用Cache。Atlas中对Web Service的调用也可以利用这一Cache机制,以减少服务器端不必要的开销。
要启用Web Service的Cache,您只需要在WebMethod的声明中添加如下属性:
![None.gif](/Images/OutliningIndicators/None.gif)
其中CacheDuration的值代表Cache的时间,单位为秒。
但这种Cache的方法是Web Service提供的,Atlas对此一无所知,每次调用还是被发送给服务器。所以对于网络上延迟对用户的影响,这种Cache没有办法改善。
让我们通过一个示例程序进一步了解Web Service的Cache。
首先编写一个Web Service,返回当前时间,并指定CacheDuration为5秒:
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![ContractedBlock.gif](/Images/OutliningIndicators/ContractedBlock.gif)
![dot.gif](https://www.cnblogs.com/Images/dot.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![ContractedSubBlock.gif](/Images/OutliningIndicators/ContractedSubBlock.gif)
![dot.gif](https://www.cnblogs.com/Images/dot.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockEnd.gif](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![ExpandedBlockEnd.gif](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
然后创建一个Atlas页面,添加ScriptManager并在其中引用这个Web Service:
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
再添加一些HTML标记用来调用这个Web Service并且显示结果:
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
最后是JavaScript部分,这里我们将每一次调用的结果都显示到页面上,便于分析:
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![ContractedBlock.gif](/Images/OutliningIndicators/ContractedBlock.gif)
![dot.gif](https://www.cnblogs.com/Images/dot.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedBlockEnd.gif](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![ContractedBlock.gif](/Images/OutliningIndicators/ContractedBlock.gif)
![dot.gif](https://www.cnblogs.com/Images/dot.gif)
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedBlockEnd.gif](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
下面在浏览器中测试一下,在多次点击按钮后,结果如下,可以看到Cache的作用:
![cachedws1.JPG](https://i-blog.csdnimg.cn/blog_migrate/109421015fdc778f4f0ead37f5c6266e.jpeg)
同时,在Fiddler中可以看到,实际上这些请求还是被发送到了服务器,Cache只是服务器端的实现:
本示例的源代码可以在此下载:http://files.cnblogs.com/dflying/CachedWebServiceDemo.zip