Reducing server response time, using the platform cache

Redundant SOQL can be expensive, and you can significantly improve performance by using the platform cache feature of the Salesforce Lightning platform. Salesforce offers two types of caching mechanisms namely Org cache and session cache:

  • Session cache: This caches data for a user session, and the cache expires once the user session expires.
  • Org cache: This is accessible across sessions, requests, and Org users and profiles. You can set an expiration time for this type of cache.

The document here (https://developer.Salesforce.com/docs/atlas.en-us.Apexcode.meta/Apexcode/Apex_platform_cache_limits.htm) shows the size of the cache that's available for each Salesforce edition Org. You can purchase additional caching if needed.

The following is a simple code example of how you can leverage the CacheBuilder interface to cache API calls in Org cache: 

public class APIResultCache implements Cache.CacheBuilder {
public Object doLoad(String parameters) {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-Apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
return response.getBody();
}else{
return 'call Failed';
}
}
}

Now you can retrieve the cached results, using the following code snippets for session and Org caches, respectively:

String animals = (String) Cache.Org.get(UserInfoCache.APIResultCache, 'key');//From Org cache

User animals = (String) Cache.Session.get(UserInfoCache.APIResultCache, 'key');//From Org cache

//Use following for retrieval from partition cache

User animals = (String) Cache.Partition.get(UserInfoCache.APIResultCache, 'key');//From Org cache
We won't be digging much into the platform cache in Apex, as this is beyond the scope of this book. However, there are great resources provided in the Apex implementation guide (https://developer.Salesforce.com/docs/atlas.en-us.Apexcode.meta/Apexcode/Apex_cache_namespace_overview.htm).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.180.43