2011-07-18 46 views
3

我正在尝试实现一个测验应用程序。应用程序逐个加载ajax的问题​​。当用户点击“到下一个问题”按钮时,他/她的答案被保存在缓存中。但是,当我调试,缓存列表始终为空...在Play Framework中使用缓存

此代码创建第一个缓存阵列:

public static void viewQuiz(@Required String user, @Required String test) {   
     if(validation.hasErrors()) { 
      flash.error("Hoop kullanıcı lazım…"); 
      index(); 
     } else{ 
      TestClass selectedTest = TestClass.find("title", test).first(); 
      List<String> choiceList = new ArrayList<String>(); 
      session.put("testID", selectedTest.id); 
      Cache.set("choices", choiceList, "30mn"); 
      render(); 
     } 
    } 

而这种代码试图保存答案逐一:

public static void question(@Required Long id, String answer){ 
    Long testId = Long.parseLong(session.get("testID")); 
    TestClass test = TestClass.findById(testId); 
    List<Question> questList = Question.find("test_id", test.id.intValue()).fetch(); 
    Question quest = questList.get(id.intValue()); 
    if(answer != null){ 
     List<String> choiceList= Cache.get("choices",List.class); 
     choiceList.add(id.intValue(), answer); 
     Cache.set("choices", choiceList, "30mn"); 
    } 
    int count = questList.size()-1; 
    render(quest, count, id); 
} 

而这个代码是第二次的HTML视图:

#{extends 'main.html' /} 

#{set title:'question.html' /} 

<script type="text/javascript"> 
     var questionId = ${id}; 
     $('#nextButton').click(function(){ 
     $('#questionDiv').html('<p><img id = "loaderGif" src="public/images/loading.gif"/></p>'); 

     $('#questionDiv').load("/test/" + ++questionId); 

    }); 
    $('#endButton').click(function(){ 
     $('#questionDiv').html('<p><img id = "loaderGif" src="public/images/loading.gif"/></p>'); 
     $('#questionDiv').load("/result"); 
    }); 
</script> 

<legend>Soru ${id+1}</legend> 
<p>&{quest.question}</p> 

#{list items:quest.choices, as:'choice'} 
<p><input type="radio" name = "answer" id = "answer" size="30" value="${choice}"/>&{choice}</p> 
#{/list} 
#{if id < count} 
<input id = "nextButton" name="nextButton" type="button" value="İleri"/> 
#{/if} 
#{else} 
<input id = "endButton" name="endButton" type="button" value="Bitti"/> 
#{/else} 
+0

您使用的是什么版本的Play?您是使用标准内存缓存还是使用其他内容,如memcache。我还假设你在一台服务器上,因为它是开发模式,而不是多个实例之间的负载平衡。 – Codemwnci

+1

我还应该注意到,由于Play是无状态的,因此不应将高速缓存用作数据存储。如果您正在进行负载平衡,则不能保证您将返回到同一台服务器。通过记住事情,你打破了Play的无状态性质。当数据已经存在于数据库中时,最好使用缓存,但是用于最大限度地减少频繁的数据库读取。# – Codemwnci

+0

我正在尝试学习游戏。我正在使用Play 1.2.1,并且不更改任何缓存设置。我在使用mysql的Ubuntu本地主机上。 –

回答

13

不要使用缓存来“存储”对象。可以将它存储在会话中,也可以创建一个新模型来存储答案。通常,您不能指望缓存保留您放入的对象;它是一个缓存,而不是一个商店。

要引用Play!网站:当 你把数据在缓存中,你不能指望这些数据保留在那里 永远:http://www.playframework.org/documentation/1.2.2/cache

明白缓存合同显然是很重要的。其实你不应该。缓存速度很快,但值过期,并且缓存通常只存在于内存中(没有持久性的 备份)。

+0

+1实际参考文档。 – Jasper

2

Cache是​​不可靠的,你可能会得到它作为null开发模式。这是预期的,您可以尝试将其更改为prod模式并查看其行为。

+0

我无法在prod模式下使用eclipse进行调试。它锁定某处,但我找不到... –

+0

听起来很奇怪,开发模式会产生不同的结果prod模式。 –