Working with Cache

Enonic version: 6.11.1
OS: Win10

Hi,

I’ve been looking at doing some caching in my project, and I seem to have hit a roadblock…
How do I open existing cache instances?

Right now I’m doing it as such, within the part using the cached data:

var cache = libs.cache.newCache({
    size:   100,
    expire: 3600
});

var a = cache.get('mykey', function() {
    return generatorfunction()});

Checking the size of the cache, this will successfully save the data from the generatorfunction.
The code above will trigger on each GET request for this specific part. But this seems to be only creating a new empty cache instance on each request.

Do I need to structure it differently?

Looking at the cache docs, I cant seem to find an answer to my question.

Hi Martin,

Where do you define your newCache variable cache? It needs to be defined outside of the scope of any exported .get or .post method in your controller.

2 Likes

Ah! That seems to have done the trick. Perfect.
I had it within the GET request… :slight_smile:

1 Like

Nice =)

Good it was that easy to fix.

Code outside the request handlers will be initiated only once, while code inside the handlers will be triggered each time that specific request method is sent. So basically you created a new temporary cache and filled it for each request. We could definitely improve the docs on that part.

Update: thanks to @aro I’ve managed to add a little note about just that in the docs for using lib-cache. Hope it helps others.

This topic was automatically closed after 24 hours. New replies are no longer allowed.