Playframework 如何清除Play Framework 2.1中的所有缓存

Playframework 如何清除Play Framework 2.1中的所有缓存,playframework,playframework-2.1,Playframework,Playframework 2.1,因此,我正在使用Play的内置缓存API,如下所示: 在我的代码中,我已经将缓存设置为每10分钟过期一次。我还使用会话缓存样式 所以我的主要问题是,由于跟踪所有缓存非常困难,我如何清除所有缓存?我知道使用Play的默认缓存是最小的,但在这一点上它对我来说非常好。我只希望能够在一段时间内清除缓存一次,以防进行了太多的会话,并且在我的代码中的某个地方缓存堆积起来。没有提供清除整个缓存的方法 您必须使用自己的缓存插件或扩展插件来提供此功能。您可以编写Akka系统调度程序和Actor,在给定的时间间隔内

因此,我正在使用Play的内置缓存API,如下所示:

在我的代码中,我已经将缓存设置为每10分钟过期一次。我还使用会话缓存样式

所以我的主要问题是,由于跟踪所有缓存非常困难,我如何清除所有缓存?我知道使用Play的默认缓存是最小的,但在这一点上它对我来说非常好。我只希望能够在一段时间内清除缓存一次,以防进行了太多的会话,并且在我的代码中的某个地方缓存堆积起来。

没有提供清除整个缓存的方法


您必须使用自己的缓存插件或扩展插件来提供此功能。

您可以编写Akka系统调度程序和Actor,在给定的时间间隔内清除缓存,然后将其设置为在全局文件中运行。没有列出所有密钥的方法,但我使用调度程序作业通过使用缓存来管理清除缓存。请在我的缓存密钥列表中手动删除。如果使用的是移动的缓存模块。一些缓存模块有一个api来清除整个缓存。

下面是一个例子,如果您使用默认的EhCachePlugin

import play.api.Play.current

...

for(p <- current.plugin[EhCachePlugin]){
  p.manager.clearAll
}
导入play.api.play.current
...

感谢@alessandro.negrin指出如何访问EhCachePlugin

以下是该方向的一些进一步细节。使用Play 2.2.1 default EhCachePlugin进行测试:

  import play.api.cache.Cache
  import play.api.Play
  import play.api.Play.current
  import play.api.cache.EhCachePlugin

  // EhCache is a Java library returning i.e. java.util.List
  import scala.collection.JavaConversions._

  // Default Play (2.2.x) cache name 
  val CACHE_NAME = "play"

  // Get a reference to the EhCachePlugin manager
  val cacheManager = Play.application.plugin[EhCachePlugin]
    .getOrElse(throw new RuntimeException("EhCachePlugin not loaded")).manager

  // Get a reference to the Cache implementation (here for play)
  val ehCache = cacheManager.getCache(CACHE_NAME)
然后您可以访问缓存实例方法,如

  // Removes all cached items.
  ehCache.removeAll()
请注意,这与@alessandro.negrin所描述的不同 根据文档:“清除CacheManager中所有缓存的内容,(…)”, 可能不是“播放”缓存

此外,您还可以访问缓存方法,例如
getKeys
,这些方法可能允许您 选择包含
匹配字符串的键子集,例如执行删除操作以:

  val matchString = "A STRING"

  val ehCacheKeys = ehCache.getKeys() 

  for (key <- ehCacheKeys) {
    key match {
      case stringKey: String => 
        if (stringKey.contains(matchString)) { ehCache.remove(stringKey) }
    }
  }
val matchString=“一个字符串”
val ehCacheKeys=ehCache.getKeys()
(钥匙)
if(stringKey.contains(matchString)){ehCache.remove(stringKey)}
}
}

将用于缓存的所有密钥存储在一个集合中,例如HashSet,当您要删除整个缓存时,只需迭代该集合并调用

Iterator iter = cacheSet.iterator();
while (iter.hasNext()) {
   Cache.remove(iter.next());
}

在Play 2.5.x中,用户可以直接访问
EhCache
缓存管理器提供程序,并使用完整的
EhCache
API:

import com.google.inject.Inject
import net.sf.ehcache.{Cache, Element}
import play.api.cache.CacheManagerProvider
import play.api.mvc.{Action, Controller}

class MyController @Inject()(cacheProvider: CacheManagerProvider) extends Controller {
    def testCache() = Action{
        val cache: Cache = cacheProvider.get.getCache("play")
        cache.put(new Element("key1", "val1"))
        cache.put(new Element("key2", "val3"))
        cache.put(new Element("key3", "val3"))
        cache.removeAll()
        Ok
    }
}

谢谢你的输入。我知道清除缓存的一种方法是重新编译代码。你是如何清除缓存的?