Playframework之cache

本文详细介绍了Play容器启动时如何检查Memcached配置并进行相应初始化,包括Memcached的开启与配置,以及Play框架内Ehcache的配置与使用,最后提供了自定义Cache实现的方法。

Cache实现

Play容器启动时(play.Play.start()),调用play.cache.Cache.init()

检查application.conf配置文件中,是否开启了memcached

           a) 未开启memcached则开启一个ehcache实例

           b) 若开启memcached但连接memcached失败,则会启动一个ehcache

Cache使用memcached配置

配置一个memcached

memcached=disabled (开启 enabled,关闭disabled)

memcached.host= 127.0.0.1:11211

memcached.user=username

memcached.password=password

配置多个memcached

memcached=disabled (开启 enabled,关闭disabled)

memcached.1.host= 127.0.0.1:11211

memcached.2.host= 127.0.0.1:11211

play中Ehcache的配置

配置文件playframework/src/ehcache.xml

 

maxElementsInMemory="10000"             //内存中最大缓存对象数

eternal="false"                         //Element是否永久有效,一但设置了,timeout将不起作用

timeToIdleSeconds="120"                 //设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。

timeToLiveSeconds="120"                 //设置Element在失效前允许存活时间。最大时间介于创建时间和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大。

overflowToDisk="false"                  // 当缓存中元素的数量超过限制时,就把这些元素持久化到硬盘,如果overflowToDisk是false ,那么maxElementsOnDisk 的设置就没有什么意义了

maxElementsOnDisk="10000000"            //持久化该缓存的元素到硬盘上的最大数量

diskPersistent="false"                  //Whether the disk store persists between restarts of the Virtual Machine.

diskExpiryThreadIntervalSeconds="120 "  //磁盘失效线程运行时间间隔,默认是120秒

memoryStoreEvictionPolicy="LRU"         //当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)

 

自定义ehcache配置

在app目录下面,新建ehcache配置的xml文件ehcache.xml

     

自定缓存实现Cache

自定义一个playPlugin

重写 play.PlayPlugin.onLoad()

在onLoad方法中,设置Cache属性 play.cache.Cache.forcedCacheImpl

     参见源码: play.cache.Cache.init()和play.Play.start()

 

Play自带的controller缓存

play自带了controller缓存,play.cache.CacheFor 在controller方法上加上注解后,play将会为方法提供缓存(源码:play.mvc.ActionInvoker.invoke(Request, Response))

// Check the cache (only for GET or HEAD)

if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {

    cacheKey = actionMethod.getAnnotation(CacheFor.class).id();

    if ("".equals(cacheKey)) {

        cacheKey = "urlcache:" + request.url + request.querystring;

    }

    actionResult = (Result) play.cache.Cache.get(cacheKey);

}


转载于:https://my.oschina.net/u/923508/blog/389537

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值