Sim*_*mon 5 scala playframework anorm playframework-2.0
我看到anorm不是一个ORM框架,它直接通过SQL查询数据.对于大多数应用程序/网站,我们不应该每次都查询数据库,我们需要通过SQL或项目ID来缓存数据.我想知道playframework是否提供了任何类型的缓存机制?如果不是如何添加它?
谢谢.
nde*_*rge 10
在查询数据库之前,您可以在控制器中使用Play缓存.以下是从Play缓存文档和Scala API派生的简单示例:
val user: User = Cache.getOrElse[User](key = "user" + userId, expiration = 10) {
User.findById(userId)
}
Run Code Online (Sandbox Code Playgroud)
在此代码中,在尝试查询数据库之前,我们在缓存中进行查找以检查用户之前是否尚未加载.如果在缓存中找不到,我们将其存储在缓存中,并在10秒内到期.
您可以简单地缓存Anorm方法的答案.例如,我使用的真实方法:
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
代码执行选择并将答案存储在缓存中getOrElse.如果该值在Cache中,则将被识别并且不会执行任何查询.
唯一的问题是,当您更新实体用户时,您将不得不更新缓存(因此它不会保留过时的数据):
// 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)
Run Code Online (Sandbox Code Playgroud)