简体   繁体   English

如何在Playframework中使用anorm时添加缓存机制

[英]How to add cache mechanism when using anorm in Playframework

I see anorm is not a ORM framework, it is querying data directly by SQL. 我看到anorm不是一个ORM框架,它直接通过SQL查询数据。 For most of the application/website, we should not query the database everytime, we needs to cache the data either by SQL or item id. 对于大多数应用程序/网站,我们不应该每次都查询数据库,我们需要通过SQL或项目ID来缓存数据。 I wonder whether playframework has provided any kind of caching mechanism? 我想知道playframework是否提供了任何类型的缓存机制? If not how to add it? 如果不是如何添加它?

Thanks. 谢谢。

You can use the Play cache in your controller, before querying your database. 在查询数据库之前,您可以在控制器中使用Play缓存。 Here is a straightforward example derived from the Play cache documentation and the Scala API : 以下是从Play缓存文档Scala API派生的简单示例:

val user: User = Cache.getOrElse[User](key = "user" + userId, expiration = 10) {
  User.findById(userId)
}

In this code, before trying to query the database, we make a lookup in the cache to check if the User has not been loaded previously. 在此代码中,在尝试查询数据库之前,我们在缓存中进行查找以检查用户之前是否尚未加载。 If not found in the cache, we store it in the cache with an expiration in 10 seconds. 如果在缓存中找不到,我们将其存储在缓存中,并在10秒内到期。

You can simply cache the answer of the Anorm methods. 您可以简单地缓存Anorm方法的答案。 For example, real method that I use: 例如,我使用的真实方法:

def findById(id: Long): Option[User] = {
    Cache.getOrElse(userCacheKey + id, 60*60) {
      DB.withConnection {
        implicit connection =>
          SQL("select * from publisher where id = {id}").on('id -> id).as(User.simple.singleOpt)
      }
    }
}

The code does the Select and stores the answer in the cache via getOrElse . 代码执行选择并通过getOrElse将答案存储在缓存中。 If the value is in the Cache, it will ber etrieved and no query will be executed. 如果该值在Cache中,则将被识别并且不会执行任何查询。

The only issue is that when you update the entity User you'll have to update the cache (so it doesn't keep stale data): 唯一的问题是,当您更新实体用户时,您将不得不更新缓存(因此它不会保留过时的数据):

// Assumes a user: User object available with the updated user
Cache.set(userCacheKey + id, cached.copy(name = user.name, avatar = user.avatar, bio = user.bio, url = user.url, location = user.location), 60*60)

Assuming you are using Play2 framework, it indeed does provide a cache mechanism. 假设您使用的是Play2框架,它确实提供了缓存机制。 It has nice documentation here: 它有很好的文档:

http://www.playframework.org/documentation/2.0/JavaCache (its called javacache, but it works from Scala) http://www.playframework.org/documentation/2.0/JavaCache (它叫做javacache,但它适用于Scala)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM