【问题标题】:Play - Sharing objects among requests with no need for persistencePlay - 在请求之间共享对象,无需持久化
【发布时间】:2014-11-12 01:27:23
【问题描述】:

在我的 Play 应用程序中,我需要在多个请求之间共享一些对象,但不需要任何类型的长期持久性。这些物品太大了,不能塞进饼干里。我可以将它们序列化到关系数据库,但这对我的需求来说似乎很重:以某种方式说“将此对象保留 10 分钟,使其可供所有线程访问,然后将其丢弃就足够了”

我该怎么做?

【问题讨论】:

  • 我查看了缓存——我不知道一个对象保存了多长时间。我怎么知道它会持续 10 分钟?
  • 使用Cache.set,您可以将 TTL 设置为您想要的任何值。

标签: playframework


【解决方案1】:

Google Guava 系列非常适合您的要求。您可以在内存缓存中创建过期。 Guava Explained 和链接中的示例:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
   .maximumSize(1000)
   .expireAfterWrite(10, TimeUnit.MINUTES)
   .removalListener(MY_LISTENER)
   .build(
       new CacheLoader<Key, Graph>() {
         public Graph load(Key key) throws AnyException {
           return createExpensiveGraph(key);
         }
       });

或者,您可以使用ConcurrentHashMap 自己实现缓存。

【讨论】:

  • 很好的答案!如果我能接受两个,我会的。我接受了第一个,因为它内置在 Play 中,但这显然也是一种强大而简单的方法。
【解决方案2】:

Play 的缓存 API 已经足够了。它使用 EHCache(内存缓存)作为默认实现。

玩 Scala:

import play.api.cache.Cache

val hugeList: List[String] = ...

Cache.set("keyName", hugeList, 600) // Caches `hugeList` as "keyName" for 10 minutes (600 seconds)

Cache.getAs[List[String]]("keyName") // Returns `Option[List[String]]` with the value if "keyName" is cached, otherwise `None`.

Cache.remove("keyName") // Removes this key from the cache.

玩 Java:

import play.cache.Cache;

Cache.set("keyName", hugeList, 600); // Works exactly the same as the scala version.

Cache.get("keyName");  // Returns the cached value or `null`.

Cache.remove("keyName");  // Same as scala version.

还要确保在您的build.sbtBuild.scala 中的libraryDependencies 中包含cache

API 文档:ScalaJava

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多