2011-07-18 47 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模式。 –