简体   繁体   English

如何在play framework 2.1中保留对象

[英]how to preserve a object in play framework 2.1

my problem is that I need to preserve a list of objects that were obtained from an A controller , this controller to send the ID of objects and some basic data of these in VIEW , in the view I need to select an row (depicting an object in the list) to be stored in a database, then this ID is taken to a controller B which calls the list of objects preserved and is obtained for selected object in the database then save. 我的问题是我需要保留从A控制器获取的对象列表,该控制器在VIEW中发送对象的ID和这些对象的一些基本数据,在视图中 ,我需要选择一行(描述一个对象在列表中)存储到数据库中,然后将此ID带到控制器B控制器B调用保存的对象列表,并从数据库中的选定对象中获取该对象,然后保存。

    Controller A{

     List<X> listX = math_function();
     return ok( _view.render(listX)); 

    }

    view.scala.html

    @for(listX -> X){
      <td id="@x.id"> @x.name</td>
    }

    Controller B{
...
     listX = getPreserveLists();
     x = ListX.get(get_id);
     x.save()
...
    }

I would like to know how to preserve these objects. 我想知道如何保存这些对象。 Thanks. 谢谢。

You can preserve them into KVM(like redis ) but I don't recommend the way because you compute them in controller, means it does not takes much time. 您可以将它们保存到KVM(如redis )中,但是我不建议这样做,因为您在控制器中对其进行计算,这意味着不会花费很多时间。 So, you should compute them every time. 因此,您应该每次计算它们。

If math_function takes huge time, you should not do them in controller. 如果math_function需要大量时间,则不应在控制器中进行操作。 Do it out of http request(like batch) and store results in DB, KVM, etc... or Memoize the function. 从http请求(例如批处理)中执行此操作,并将结果存储在DB,KVM等中……或记忆该功能。

One option is to use the play.api.cache.Cache object described here . 一种选择是使用此处描述的play.api.cache.Cache对象。

You could store data in the cache: 您可以将数据存储在缓存中:

// if listX could be different for every user, 
// you could use user.login as a key
Cache.set(user.login, listX) 

And then you could retrieve listX later: 然后您可以稍后检索listX

val maybeLisX: Option[List[X]] = Cache.getAs[List[X]](user.login)

I would like to add that this is only worth doing if computing listX is an expensive operation. 我想补充一点,这仅在计算listX是一项昂贵的操作时才值得做。 You definitely don't want to do this if listX could be different for the same input. 如果listX对于相同的输入可能不同,则您绝对不希望这样做。 In that case, you should recompute listX. 在这种情况下,您应该重新计算listX。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM