使用 Play Framework 的缓存 API 在多语言网站中缓存操作 [英] Caching an action in a multi-language website using Play Framework's Cached API
问题描述
为了在给定的秒数内缓存每个标签和语言的动作,我编写了以下辅助方法(其中标签是我给动作的名称):
In order to cache actions per label and language for a given number of seconds, I wrote the following helper method (where label, is the name I give to my action):
def cacheResponseFor(label: String, duration: Int)(action: EssentialAction) = {
Cached({r: RequestHeader => (label + getLanguage(r))}, duration){ action }
}
def getLanguage(request: RequestHeader): String = {
request.cookies
.get(helpers.SessionHelpers.LANGUAGE_SESSION)
.map(_.value)
.getOrElse(helpers.LanguageHelpers.FRENCH)
}
但是我遇到了一些奇怪的事情,当我尝试缓存 60 年代的 Action
并同时将语言从法语切换到英语时,我一直在 60 年代获得法语版本,然后它切换到英语.
But I'm experiencing something weird, when I try to cache an Action
for 60s and switch languages in the meantime to English from French for example, I keep getting the French version for 60s then it switches to english.
经过调查,我发现方法 getLanguage
不会在每次调用该操作时调用,就好像 Key 仅在缓存期结束后评估一样.
After investigating, I found that method getLanguage
is not called at each call to that action as if the Key gets evaluated only after the caching period ends.
这是不对的,我希望每次请求我的页面时都调用这个 cacheResponseFor
,使用 getLanguage
评估语言,然后我得到正确的缓存版本,即我应该得到 2 个缓存操作(每种语言一个).
This is not right, I would want this cacheResponseFor
to be called everytime I request my page, the language gets evaluated using getLanguage
and I get the right cached version, i.e. I should end up with 2 cached actions (one per language).
我错过了什么吗?
推荐答案
我不知道您面临的问题是什么,但我做了一个小的概念验证,完全没有问题.
I do not know what is the issue you are facing but I did a small proof of concept and there is no issue at all.
package controllers
import play.api.cache.Cached
import play.api.mvc.{Action, Controller, EssentialAction, RequestHeader}
object Caches {
import play.api.Play.current
def cacheResponseFor(label: String, duration: Int)(action: EssentialAction) = {
Cached({r: RequestHeader => label + getLanguage(r)}, duration){ action }
}
def getLanguage(request: RequestHeader): String = {
request.cookies
.get("language")
.map(_.value)
.getOrElse("fr")
}
}
class CachedApplication () extends Controller {
import Caches._
def index = cacheResponseFor("homePage", 60) {
Action { implicit req =>
getLanguage(req) match {
case "fr" =>
Ok("Bonjour le monde")
case _ =>
Ok("Hello world")
}
}
}
}
这篇关于使用 Play Framework 的缓存 API 在多语言网站中缓存操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!