Shared cache

Shared cache is a high-performance distributed and replication cache system built for faster access to code service data. 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; 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 shared cache API

Learn how to use shared cache

Learn how to use shared cache using the ClearBlade library

TTL

Time to live (TTL) is when a cache expires if SET or SETNX is not called within that 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 the shared cache, then call the 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 a subscribed topic, storing message data in shared cache, and then calling the 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 the fetched collection and 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) { // document the value is a string const entityToCompare = JSON.parse(jsonData[k]) // compare entities from the collection with those from the message payload }) } }) }