Session Cache Example

Let us consider the following scenario:

Whenever the user logs in to the system, the list of accounts belonging to the user needs to be loaded in memory and made available for all further requests coming to the system for that user.

This is a typical scenario that demands the need for a session level cache. For a session level cache, the cache handler needs the SessionInfo for the logged in user. From the SessionInfo, it can retrieve all information related to the user and use it for data fetching purposes.

A typical CacheDataBuilder for this scenario will look like:

public class UserAccountsCacheDataBuilder extends CacheDataBuilder
{
	protected List initializeCache(HashMap params)
		{
			SessionInfo sessInfo = (SessionInfo)params.get(CacheConstants.OBJECT_SESSIONINFO);
			String userNumber = sessInfo.userNo;
			String gcif = sessInfo.sCustNo;
			// Execute your logic to get the list of accounts linked to this user.
			List<AccountVO> userAccounts = getUserAccountsFor(userNumber, gcif);
			return userAccounts;
		}
} 


Now that we have the CacheDataBuilder ready, let us proceed to define the cache as follows:

<Cache Id="USER_ACCOUNTS_CACHE" Scope="session">
	<Handler>com.myapplication.UserAccountsCacheDataBuilder </Handler>
</Cache> 


To consume this cache from the application code, the following sample code is provided:

List<AccountVO> userData = CacheManager.getInstance().getDataFromCache(session, "USER_ACCOUNTS_CACHE");
	for (AccountVO obj : userData)
		{
			//Perform your application logic here...
		} 


The key aspect around Session Cache is that the data for the Session cache is stored in a key that is dynamically created in the Session. Hence, it is necessary to always pass the HttpSession object for retrieving data from this cache.

Let us consider a variant of the requirement for the given scenario:

Once the user submits a new Deposit Account request, the account created should be immediately visible across all modules where the Deposit Accounts are displayed.

This cache definition still does not meet the necessary requirement as the cache is loaded when accessed first time and then will not contain the newly opened Deposit Account within that session.

To do this, as part of the process flow for the Deposit Account creation, the application just has to execute the following API as follows:

CacheManager.getInstance().invalidateCache(session, "USER_ACCOUNTS_CACHE");

The API call will clear out the data from the session for this cache. As a result, the cache gets reloaded when the user accesses any application flow that requires the usage of this cache.