Message Boards

Add caching to REST Builder

Pietro Pagani, modified 3 Years ago.

Add caching to REST Builder

New Member Posts: 7 Join Date: 10/8/19 Recent Posts

Hi all,
I have implemented a couple of endpoint with REST Builder which expose data fetched from an external datasource.
Since the data don't change very often, I would like to enable caching, so I injected a singleVMPool within my component

@Reference
private SingleVMPool _singleVMPool;
private static PortalCache<String, List<Building>> _portalCache;

and then in its initialization method (marked with @Activate) I added something like:

_portalCache = (PortalCache<String, List<MyObject>>) _singleVMPool.getPortalCache("MyCache");

After that I properly configured cache in XML

<ehcache dynamicConfig="true" monitoring="off"
	name="module-single-vm" updateCheck="false"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd">
	<cache eternal="false" maxElementsInMemory="10000"
		name="MyCache" overflowToDisk="false"
		timeToIdleSeconds="600">
	</cache>
</ehcache>

The problem is that the component has been created automatically by REST Builder and is marked as "scope = ServiceScope.PROTOTYPE"
This means that at each requests, a new instance of the component will be created and hence a new cache will be initialized: what happens at the end is that my cache is always empty.

Is it possible to avoid marking REST Builder component as scope = ServiceScope.PROTOTYPE? Or shall I configure cache in a different way?

thumbnail
Javier De Arcos, modified 3 Years ago.

RE: Add caching to REST Builder

New Member Posts: 9 Join Date: 7/16/20 Recent Posts

The ResourceImpl files are always created with the ServiceScope.PROTOTYPE scope, but these files will not be regenerated if they already exist, not as the files marked with @Generated annotation.

So if you need another scope you can change it in the file and won't be modified in next generations