在Play框架中使用缓存

3
我将为您翻译以下内容:

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

以下代码创建第一个缓存数组:

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}

你使用的是哪个版本的Play?你是使用标准的内存缓存,还是使用其他东西,比如memcache?我还假设你在单个服务器上,因为它是开发模式,并且没有跨多个实例进行负载平衡。 - Codemwnci
1
我还应该指出,由于Play是无状态的,您不应将缓存用作数据存储。如果您正在进行负载平衡,则不能保证您将返回到同一台服务器。通过将事物保存在内存中,您会破坏Play的无状态性质。当数据已经存在于数据库中但被用于最小化频繁的数据库读取时,缓存是最好的选择。 - Codemwnci
我正在尝试学习Play框架。我正在使用Play 1.2.1版本,并且没有更改任何缓存设置。我在Ubuntu本地主机上使用MySQL。 - Ömer Faruk AK
2个回答

13

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

引用自 Play! 网站:http://www.playframework.org/documentation/1.2.2/cache

重要的是要了解缓存协议的明确规定:将数据放入缓存时,不能期望该数据永久驻留在那里。实际上,您不应该这样做。缓存很快,但值会过期,并且缓存通常仅存在于内存中(没有持久备份)。


2

缓存不可靠,您可能在开发模式下得到它为空。这是预期的,您可以尝试将其更改为生产模式并查看其行为。


我无法在生产模式下使用Eclipse进行调试。它在某个地方被锁定了,但我找不到原因... - Ömer Faruk AK
对我来说,开发模式和生产模式会产生不同的结果听起来很奇怪。 - Robert de W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接