4

I have been trying to use the Org cache but for some reason cached item is getting removed in the subsequent requests. Below is the code which i wrote inside the controller class

if (!Cache.Org.contains('TestKey'))
{                
    DateTime dt = DateTime.parse('06/16/2015 11:46 AM');                
    Cache.Org.put('TestKey', dt);    
}

The above code is not throwing any exception. If i access the cached item in the same request, it brings up. But for a new request, it doesn't show and results into adding the item to cache again. I also tried enabling cache diagnostics to see if there are any cached items, but don't see it.

  • Same happens with me.. Is there any problem with the cache? – Ataullah Khan Feb 21 '17 at 10:29
2

When you created the org cache partition did you set it as default? If you haven't, then you should use the full namespace.partion prefix when accessing your key as explained here:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_platform_cache_org_examples.htm

"To refer to the default partition and the namespace of the invoking class, omit the namespace.partition prefix and specify the key name."

So the format will be something like below. You need to replace YOUR_PARTITION_NAME with the name of the partition you created - How to create partition see here:

https://help.salesforce.com/apex/HTViewHelpDoc?id=data_platform_cache.htm

public DateTime getDateFromCache(){

        DateTime date_time_from_cache;

        //check in the cache first
        if (Cache.Org.contains('local.YOUR_PARTITION_NAME.TestKey')){
            system.debug('## getting values from cache');
            date_time_from_cache = (DateTime) Cache.Org.get('local.YOUR_PARTITION_NAME.TestKey');
        }
        else{ 
            system.debug('## setting values to cache');
            date_time_from_cache = DateTime.newInstance(2016, 2, 25, 12, 48, 0);
            Cache.Org.put('local.YOUR_PARTITION_NAME.TestKey', date_time_from_cache);
        }

        return date_time_from_cache;

}

system.debug(getDateFromCache());

You can run above block (after placing the correct partition in your code) in execute anonymous. You will notice that the first time you run it, you will see:

|DEBUG|## setting values to cache

subsequent execution of the block will retrieve the value from cache

|DEBUG|## getting values from cache

hope this helps

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.