cache across multiple resource,Cache issue across multiple APIs

So I am using Global cache across multiple APIs:

1. In first API call i am setting expiry time to say "180" sec in populate cache policy,

2. In second API call I am doing a "lookup" updating data in cache and then again "populating" the same cache. This time without "<ExpirySettings>" tag.

My question is will above scenario persist the same expiry time which i set in first call, as in my case it is not behaving like that.

I want same expire time which i set in first call to persist across all API calls?

is there any away to do this?

0 1 148
1 REPLY 1

I think if ExpirySettings not present then expiry value configured in cache instance will be used. You can try following

1. Store created timestamp along with cache data initially.

2. In subsequent call (that is when loockup cache was successful & cache is present) extract created timestamp from cache and calculate new ttl. (New ttl = Current timestamp - timestamp extracted from cache).

We had similar requirement (https://community.apigee.com/questions/59935/ip-address-based-soft-lock.html) and this approach is worked. Find sample javascript & Populate policy code below.

JS code:

var cache = context.getVariable('cache');
var currentTimestamp = context.getVariable('system.timestamp');
var ttl = 180;
if(cache !== null) { 
   cache=JSON.parse(cache);
   cache.cachData = <YOUR CACHE DATA>
   var timeDiff = currentTimestamp/1000 - cache.createdAt/1000;
   print ("timeDiff == " + timeDiff);
   ttl =  Math.floor(180 - timeDiff);
   if(ttl <= 0) {
	   ttl = 1;
   }
} else {
	
	cache = {};
	ccache.cachData = <YOUR CACHE DATA>
	cache.createdAt = currentTimestamp;
}
cache.ttl = ttl;
print("err cache = " + JSON.stringify(cache));
context.setVariable('cache', JSON.stringify(cache));
context.setVariable('cacheTtl', ttl.toString());
	  

Policy:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PopulateCache async="false" enabled="true" name="PC-Populate" continueOnError="false">
    <DisplayName>PC-Populate</DisplayName>
    <Properties/>
    <CacheKey>
        <KeyFragment ref="cacheKey"/>
    </CacheKey>
    <CacheResource>cache</CacheResource>
    <Scope>Global</Scope>
    <ExpirySettings>
        <TimeoutInSec ref="cacheTtl"/>
    </ExpirySettings>
    <Source>ipCache</Source>
</PopulateCache>