Redis is cool because it (1) is crazy fast, (2) lets you store just about anything at a key, and (3) provides safe, atomic operations. Use Redis for things like caching, message queues, counters, scoreboards, and session data.
You can play with Redis in an online sandbox or install a redis server on your own machine (on macOS, brew install redis
) The online sandbox has a small tutorial. You can also work through the Redis tutorial by TutorialsPoint.
After installing, run redis-server
(preferably in the background), then run redis-cli
to start entering commands.
Using Redis is all about issuing commands. Try these out:
$ redis-cli 127.0.0.1:6379> ping PONG 127.0.0.1:6379> set favoritecolor blue OK 127.0.0.1:6379> set classyear senior OK 127.0.0.1:6379> set count 50 OK 127.0.0.1:6379> incr count (integer) 51 127.0.0.1:6379> get count "51" 127.0.0.1:6379> incr x (integer) 1
Five types:
You should be aware of, and consult frequently, the official documentation on all of the Redis commands.
So how to write an application that uses Redis? Let’s look at a couple examples.
You can use this Redis library.
import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) print(r.set("color", "purple")) print(r.incrby("dogs", 3)) print(r.get("dogs")) print(r.lpush("friends", "lauren")) print(r.rpush("friends", "josh")) print(r.hmset("words", {"blue": "azul", "green": "verde", "red": "rojo"})) print(r.hget("words", "green")) print(r.hkeys("words")) print(r.lrange("friends", 0, -1))
You can use this Redis client for Node.
const redis = require('redis'); const client = redis.createClient({host: 'localhost', port: 6379, db: 0}); client.on('error', error => { console.error(error); }); client.set('color', 'purple', (err, reply) => console.log(reply)); client.incrby('dogs', 3, (err, reply) => console.log(reply)); client.get('dogs', redis.print); client.get('ThisWillFailWithTooManyArgsToGet', 'extra', 'Arguments', redis.print); client.lpush('friends', 'lauren', redis.print); client.rpush('friends', 'josh', redis.print); client.hmset('words', 'blue', 'azul', 'green', 'verde', 'red', 'rojo'); client.hget('words', 'green', redis.print); client.hkeys('words', redis.print); client.lrange('friends', 0, -1, redis.print); client.quit();