How to use platform cache - with example

Platform cache allows you to cache data in Salesforce server. Accessing platform cache is faster than getting data by querying from objects or custom settings.

Use cases

  • Storing API session token till it expires
  • Caching frequently called API response data
  • Caching results from time consuming operations like complex queries and calculations

Types of platform cache

  1. Session Cache

    Stores data in association with user’s session. Maximum life is 8 hours. Only the user who put data to this cache can retrieve it back.

  2. Org Cache

    Data is stored at the org level. Any user can access data in cache.

How to setup

  • Go to Setup -> Platform Cache
  • Click on “New Platform Cache Partition” button
  • Enter necessary details and click “Save”. You can select “Default” checkbox to make the partition your default partition to avoid specifying partition name which caching data



It is recommended to create a separate class to manage all operations with cache. You can see an example of using a service class to manage org cache below. CacheService class is used to just manage cached data and ExternalSystemAPI class leverages that class to cache access token.


/*******************************************************************************************
* @Name CacheService
* @Author Namehere
* @Date
* @Group Applicatiton Services
* @Description This class contains all service methods related to caching data in Salesforce.
* It is segregated as a service to make changing cache partition easy.
*******************************************************************************************/
/* MODIFICATION LOG
* Version Developer Date Description
*-------------------------------------------------------------------------------------------
* 1.0 Name dateHere Initial Creation
*******************************************************************************************/
public class CacheService {
/**************************************************************************************
* @Description This method gets checks for entries in org cache
* @Param String - Key string
* @Return Object - Value retrieved from org cache.
* @Example
* CacheService.getFromOrgCache('ApiToken')
**************************************************************************************/
public static Object getFromOrgCache(String cacheKey) {
if (Cache.Org.contains(cacheKey)) {
return Cache.Org.get(cacheKey);
}else {
return null;
}
}
/**************************************************************************************
* @Description This method gets checks for entries in org cache
* @Param String - Key string
* @Param Object - Value that needs to be stored to org cache
* @Return NA
* @Example
* CacheService.putInOrgCache('ApiToken','asodfua8sudf8ashdf8sdf')
**************************************************************************************/
public static void putInOrgCache(String cacheKey, Object cacheValue) {
Cache.Org.put(cacheKey, cacheValue);
}
}
/*******************************************************************************************
* @Name ExternalSystemAPI
* @Author NameHere
* @Date DateHere
* @Group External API Integrations
* @Description This class contains all callouts to external system A.
*******************************************************************************************/
/* MODIFICATION LOG
* Version Developer Date Description
*-------------------------------------------------------------------------------------------
* 1.0 Name DateHere Initial Creation
*******************************************************************************************/
public with sharing class ExternalSystemAPI {
private static final String ACCESS_TOKEN = 'accessToken';
private static final String TOKEN_EXPIRY_TIME = 'expiryTime';
/**************************************************************************************
* @Description This method returns authentication token for external System endpoints
* @Return String
* @Example
* ExternalSystemAPI.getAuthenticationToken()
**************************************************************************************/
public static String getAuthenticationToken(){
//HttpCallout
//GetResponse
//ProcessResponse and return token
}
/**************************************************************************************
* @Description This method retrives cached access token if available. If the cached
* token is not available or expired, it returns new access token.
* @Return void
* @Example
* ExternalSystemAPI.getCachedAutheticationToken();
**************************************************************************************/
public static String getCachedAutheticationToken(){
Datetime expiryTime = (Datetime)CacheService.getFromOrgCache(TOKEN_EXPIRY_TIME);
String cachedAuthenticationToken = (String)CacheService.getFromOrgCache(ACCESS_TOKEN);
if(cachedAuthenticationToken == null || expiryTime == null || System.now() > expiryTime){
return getAuthenticationToken();
}else {
return cachedAuthenticationToken;
}
}
/**************************************************************************************
* @Description This method is used to execute some action on external system
* @Param payload - Data to be sent to the other system
* @Return void
* @Example
* ExternalSystemAPI.actualAPICall(new map<Id, String>{'data' => 'value'})
**************************************************************************************/
public static void actualAPICall(Map<Id, String> payload){
//httpCallout getting header using below line
request.setHeader('Authorization', 'Bearer '+getCachedAutheticationToken())
//Set payload and send request
//Process response
}
}

2 comments: