Reputation: 865
How to use Cache.getOrElse(java.lang.String key, java.util.concurrent.Callable block, int expiration) Could someone give me a example? My point is how to use “expiration",I know it means expire time.
By the way: I want save some object to cache,and set a expire time. when the expire time,I can reset the object to the cache.
Thanks.
Upvotes: 2
Views: 1474
Reputation: 1751
Let's assume that, you want to set User
object on cache, for that you set userId
as key
and user object
as value
. If need set expiration time, for sample i set it as 30secs.
cache.set(userId, userObject, 30);
At some point of time, if you want to get user object from cache, which you set earlier using userId as key, you might try the following way to get the user object from cache.
User user = cache.get(userId);
Above will return you the user object, if you access within 30secs, otherwise it will return NULL
. This will be perfect for case like validating the session.
In some case, you frequently need to retrieve value from cache, for that following is the best approach.
User user = cache.getOrElse(userId, () -> User.get(userId), 30);
Upvotes: 1
Reputation: 1383
I use getOrElse in controllers when I have dynamic and static content to display. Cache the static and then render it together with the dynamic part:
try {
Html staticHtml = Cache.getOrElse("static-content", () -> staticView.render(), 60 * 60);
Html rendered = dynamicPage.render(arg1, arg2, staticHtml);
return ok(rendered);
} catch (Exception e) {
e.printStackTrace();
return internalServerError();
}
staticView.render()
returns some html from a view. This view should not call any other pages which are dynamic or you stash something you do not really want to stash.
60*60
means I want to store it for one hour (60 seconds times 60 minutes... ok you can write 3600
if you want)
I should add that getOrElse
gets the Object
from the cache with the specified key (in this example the key is static-content
) but if it cannot find it, then it calls the function which returns an object which is then stored for the specified amount of time in the cache with that key. Pretty neat.
Then you can call some other (dynamic) page and pass the html to it.
The dynamic stuff will stay dynamic :)
Upvotes: 0
Reputation: 486
Expiration is the number of seconds that the Object would be hold in the Cache. If you pass 0 as expiration the Cache doesn't expire and you would have to control it by hand.
What getOrElse does is check the Cache, if the Object is not there then call the callable block that you are passing and adds the result to the cache for the number of seconds that you are passing as expiration time.
I based my comment in the Play Framework Cache Javadoc.
Upvotes: 0