资源描述:
《Play Framework 框架 缓存》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、使用缓存Useacache 去创建一个高性能的系统,有时候你需要使用缓存数据。Play有一个缓存的库,当需要在分布式的系统中使用时,用的是memcached。Tocreatehigh-performancesystems,sometimesyouneedtocachedata.Playhasacachelibraryandwilluse"memcached":http://www.danga.com/memcached/whenusedinadistributedenvironment. 如果你不配置memcached,Play会使用独立的缓存,将数据存放在
2、JVM的堆中。将缓存存放在JVM的应用违反了Play的“无共享”假定:你不能在多个服务器上运行你的应用,期望这些应用的行为保持一致。每一个应用实例会有一个不同的数据拷贝。Ifyoudon’tconfigurememcached,PlaywilluseastandalonecachethatstoresdataintheJVMheap.CachingdataintheJVMapplicationbreaksthe"sharenothing"assumptionmadebyPlay:youcan’trunyourapplicationonseveralserve
3、rs,andexpecttheapplicationtobehaveconsistently.Eachapplicationinstancewillhaveadifferentcopyofthedata. 了解缓存的特点很重要:当你把数据放进缓存里的时候,你不能期望数据永远保持在那里。实际上,你不应该期望。缓存很快,但是数据会失效,而且缓存通常只存在在内存里(如果没有持久化备份的话)。Itisimportanttounderstandthatthecachecontractisclear:whenyouputdatainacache,youcan’texpe
4、ctthatdatatoremainthereforever.Infactyoushouldn’t.Acacheisfast,butvaluesexpire,andthecachegenerallyexistsonlyinmemory(withoutpersistentbackup). 所以使用缓存最好的办法是在你不需要它的时候清空它。Sothebestwaytousethecacheistorepopulateitwhenitdoesn’thavewhatyouexpect: publicstaticvoidallProducts(){ List
5、roduct>products=Cache.get("products",List.class); if(products==null){ products=Product.findAll(); Cache.set("products",products,"30mn"); } render(products);} 缓存APIThecacheAPI 缓存API是由类play.cache.Cache提供的,这个类包含了一系列的方法,可以设定,替换,得到缓存中的值。参考memcached文档区了解每个方法的确切行为。ThecacheAP
6、Iisprovidedbythe**play.cache.Cache**class.Thisclasscontainsthesetofmethodstoset,replace,andgetdatafromthecache.Refertothememcacheddocumentationtounderstandtheexactbehaviorofeachmethod. 一些例子:Someexamples: publicstaticvoidshowProduct(Stringid){ Productproduct=Cache.get(id,Product.c
7、lass); if(product==null){ product=Product.findById(id); Cache.set("product_"+id,product,"30mn"); } render(product);} publicstaticvoidaddProduct(Stringname,intprice){ Productproduct=newProduct(name,price); product.save(); showProduct(id);} publicstaticvoideditPro
8、duct(Stringid,Stringname,i