In Node.js applications, the memcached add
function is typically used when you need to store key-value pairs in a memcached server. This function only succeeds if the server doesn't already hold data for this key. It's useful when you want to ensure no existing data gets overwritten.
Here's a basic example of using memcached.add
:
const Memcached = require('memcached'); let memcached = new Memcached("localhost:11211"); let key = "username"; let value = "testUser"; // The '10' is the lifetime of the cache in seconds. memcached.add(key, value, 10, function(err) { // handle error if(err) console.error(err); });
In this code, we are connecting to a local memcached server and trying to add a key-value pair username:testUser
. If the operation is successful and there was no previous data associated with username
, the data will be stored in the cache for 10 seconds.
A more complex example might involve checking if the addition was successful or not:
memcached.add(key, value, 10, function(err) { if(err) { console.error("Failed to add:", err); } else { console.log("Added successfully"); } });
In this snippet, we use a callback function to inform us whether the addition was successful or not.
memcached.add
will not overwrite existing keys. If you want to overwrite regardless, consider using memcached.set
instead.Q: What happens if I try to add a key-value pair and the key already exists in the cache?
A: The add
function will not update the value of the key. It will simply ignore the command and your existing data tied to that key remains safe.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.