Shared Cache is a high performance distributed and replication cache system built for faster access to data in code services. This data can be shared among multiple services in the same system and can be most helpful for stream services. Each cache has a size limit of 1 MB and up to 10 caches can be created per system.
In a shared cache, everything is stored in memory and is volatile (non-persistent across platform restarts).
Find the API for shared cache
Learn how to use shared cache
Learn how to use a code service's shared cache using the ClearBlade Library
TTL
Time To Live (TTL) is the time a cache will expire if SET
or SETNX
is not called within that period of time and will return a “Key not found” error when attempting to GET
data. This is applied to an entire cache. The TTL will reset only if SET
or SETNX
operations are performed. The minimum TTL is 30.
Shared Cache Example
function testCache(req, resp) { ClearBlade.init({ request: req }); const topic = "testTopic" // Initialize the shared cache const cache = ClearBlade.Cache('sharedCacheTest'); // Fetch collection data, store each item in shared cache, then call stream service declared below ClearBlade.Collection({ collectionName: "sharedCacheCollect" }).fetch(function (err, data) { if (err) { resp.error(data); } else { data.DATA.forEach(function (d) { cache.setnx(d.item_id, d, function (err, data) { if (err) { resp.error("Failed to set initial cache: " + JSON.stringify(data)) } }) }) listenForMessages(); } }) // Stream service for listening to subscribed topic, storing message data in shared cache, and then calling process function below function listenForMessages() { const messaging = ClearBlade.Messaging(); messaging.subscribe(topic, function (err, errMsg) { if (err) { log("sub failed: " + errMsg); resp.error("sub failed"); } }); while (true) { messaging.waitForMessage([topic], function (err, msg, topic) { if (err) { resp.error("failed to wait for message: " + err); } else { log("new msg: " + JSON.stringify(msg)); const jsonMsg = JSON.parse(msg); cache.setnx(jsonMsg.item_id, jsonMsg, function (err, data) { if (err) { log("Error setting data in cache: " + JSON.stringify(data)); resp.error("Error setting data in cache: " + JSON.stringify(data)) } else { processData(jsonMsg); } }) } }); } } // Process function that fetches shared cache and uses it to compare values in fetched collection and values from message function processData(entity) { cache.getAll(function (err, data) { if (err) { resp.error("Failed to get all from cache; " + JSON.stringify(data)); } else { const jsonData = JSON.parse(data); log("resp from cache.getAll: " + JSON.stringify(jsonData)); Object.keys(jsonData).forEach(function (k) { // note: need to document that the value is a string const entityToCompare = JSON.parse(jsonData[k]) // compare entities from collection with those from message payload }) } }) }