How to implement caching with Redis
Redis is designed around the concept of data-structures and can store your dataset across strings, hashes, sorted sets, sets, lists, streams and other data structures or Redis modules.
Using Node.js, you can retrieve from and save key-value pairs with simple strings through the GET and SET commands of the client object, as shown here:
// connecting redis client to local instance.
const client = redis.createClient(6379)
// Retrieving a string value from Redis if it already exists for this key
return client.get(‘myStringKey’, (err, value) => {
if (value) {
console.log(‘The value associated with this key is: ‘ + value)
}
else { //key not found
// Storing a simple string in the Redis store
client.set(‘myStringKey’, ‘Redis Enterprise Tutorial’);
}
} });
This snippet tries to retrieve the string value associated with the myStringKey key using the GET command. If the key is not found, the SET command stores the Redis Enterprise Tutorial value for myStringKey.
The same code can be written in Python, as shown here:
# connecting redis client to local instance.
r = redis.Redis(host='localhost', port=6379, db=0)
# Retrieving a string value from Redis if it already exists for this key
value = r.get(‘myStringKey’)
if value == None: # key not found
# Storing a simple string in the Redis store
r.set(‘myStringKey’, ‘Redis Enterprise Tutorial’)
else:
print ‘The value associated with this key is: ‘, value