Introduction
What is Redis?
Redis (Remote dictionary server) is an in-memory, key-value database, commonly referred to as a data structure server, an example of a NoSQL database
Why Redis?
Reading and writing are fast since Redis stores data in memory
Mainly used for caching purpose like a memcache
Can also be used as a datastore
Key Features
Speed
Persistence
Data Structures, up to 512MB
High availability and scalability
Installation
# Mac
brew update
brew install redis
brew services start redis # start redis service
brew services stop redis # stop redis service
brew services restart redis # restart redis service
# download Redis
http://download.redis.io/
# uncompress
tar -xvf redis-stable.tar.gz
# enter Redis folder
make
# start a redis server
./src/redis-server # start redis server
CLI
# view redis host ip and port number
ps -e | grep redis
# start redis-cli interactive environment
redis-cli -h [ip] -p [port]
# command line
redis-cli [command]
# online environment
https://try.redis.io/
# Use a different port
# Edit /usr/local/etc/redis.conf
# Change port number
brew services restart redis
redis-cli -p [portNumber]
Publish/Subscribe
# client 1
subscribe channel1 # subscribe channel1
unsubscribe channel1 # unsubscribe channel1
# client 2
publish channel1 message # publish a message to the channel and client 1 will receive it from the channel
psubscribe pattern # subscribe the channels with the specific pattern
punsubscribe pattern # unsubscribe the channels with the specific pattern
pubsub channels # list the active channels
Transaction
allow the execution of a group of commands in a single step
atomic, either all of the commands or none are processed
if errors occur then the transaction is aborted
multi # start a transaction
incr count
incr count
get count
exec # execute the transaction
discard # discards all commands issued after MULTI
# will be implemented only if num is not changed
watch num
multi
incr num
get num
exec
Pipeline
Send multiple commands to the server without waiting for the replies, and finally read the replies in a single step
# command line
echo "set s v" | redis-cli
echo "set s v" | nc localhost 6379
# pass several Redis commands to a Redis server
echo "select 1\r\nset s4 v4" | redis-cli
# Client PING
# Client PING
# Client PING
# Server OK
# Server OK
# Server OK
(printf "PING\r\nPING\r\nPING\r\n"; sleep 1) | nc localhost 6379
# import from a csv file
# country.csv
# China CN
# America US
awk '{print "set " $1 " "$2}' country.csv | redis-cli
awk '{print "set " $1 " "$2}' country.csv | nc localhost 6379
awk '{print "set " $1 " "$2}' country.csv | redis-cli --pipe # bulk, one summary reply instead of one reply for each instruction
Reference