Wednesday, December 3, 2014

[Liferay] How to use Liferay Caching Mechanism using MultiVMPoolUtil

Most often, we need to use some kind of caching for our portlets. Whether it is weather data or stocks or some news feed we get from other sites. For each user who loads the web page we don't want to go to weather/stocks/news services and get new data each time. We rather cache the data for some time lets say 10 minutes and then renew whenever a user requests after 10 minutes.

So, how we should use the cache.

We have MultiVMPoolUtil which is a utility class to access MultiVMPool.
We need the above two methods (either one of them) to store our data.
All we need is a name under which the data should be stored, a key to store data and value which holds the actual data. So it is just a name, and a key-value pair. value is usually an object and name and key are strings.

How can we form name and key and How should we.. ?
We store data for some context it can be for portlet or spread over multiple portlets. Suppose my project short name is RE (short for Reporting Engine) and I need to store data for 5 reports objects which I collected from some other place. That some other place may be can named as ABC. I might keep name as reReportDataABC. I might be collecting finance report for ABC so I can choose key as ABC-finance or ABC:finance assuming there might be other types as well. ABC:staff, ABC:annual etc.. purely depends on your requirements. Last, the value would be just the object whatever holds the data. It can be a list or just an object.

So, we would need to make a call as -

public static final String RE_REPORT_DATA_ABC = 'reReportDataABC';
MultiVMPoolUtil.put(RE_REPORT_DATA_ABC, 'ABC:finance', reportsDataList);

And to get the data again
Object reportsObject = MultiVMPoolUtil.get(RE_REPORT_DATA_ABC , 'ABC:finance');

So the final code would be like this-

Now there is a catch -
The approach above will work just fine if there is just one user and user sits idle for 10 minutes and cache gets clear in the time defined (time to live : ttl), suppose that was 10 minutes. But what if there are 1000 users and cache does not get clear. The code above is not going to get live data because it was being access regularly and no idle time reaches 10 minutes.

In this case, we could just add one more key for time. See the code below.
I hope its clear now and works fine as expected.

Until next time, keep caching.. :P :)