le-*_*ude 7 java playframework playframework-2.0
我试图通过让我知道我在控制器中调用的函数的参数来制作一个更好的@Cached注释.
所以我有这个动作:
public class ContextualCachedAction extends Action<ContextualCached> {
@Override
public Result call(Context ctx) throws Throwable {
try {
String key = makeKey(ctx);
Integer duration = configuration.duration();
Result result = (Result) Cache.get(key);
if (result == null) {
result = delegate.call(ctx);
//TODO find a way to cache only successful calls
Cache.set(key, result, duration);
}
return result;
} catch (RuntimeException e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private String makeKey(Context ctx) {
//makes the key from some parameters in the ctx.request()
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我想只在它是一个Ok()时缓存delegate.call()的结果.我该如何检查?有房产吗?一个工具?或者我需要Ok().getClass().isInstance(结果)?
感谢您的任何答案和提示.
PS:我为什么要这样做?因为我有一些调用会产生几种不同类型的结果.由于我不想,因此缓存它们的结果很少是一种选择
不那么糟糕的做法:
import org.junit.*;
import static org.fest.assertions.Assertions.assertThat;
import static play.test.Helpers.*;
/* do stuff */
Result result = doSomethingWithController();
assertThat(status(result)).isEqualTo(OK);
Run Code Online (Sandbox Code Playgroud)
从2.2.2开始工作.
的ok结果实际上是play.mvc.Results.Status它封装其Scala的对方play.api.mvc.Results.Status,这反过来又其status代码设置为200.
因此,您调用result.getWrappedResult()并检查类型是否正确,将其转换为PlainResult(最小公分母)并调用status.
这看起来很丑陋:
play.api.mvc.Result wrappedResult = result.getWrappedResult();
if (wrappedResult instanceof play.api.mvc.PlainResult) {
play.api.mvc.PlainResult plainResult = (play.api.mvc.PlainResult)wrappedResult;
int code = plainResult.header().status();
if (code == OK)
// Cache
}
Run Code Online (Sandbox Code Playgroud)