author: @kawam tags:#tutorial#redis


Installation

Docker

Pull then run image.

docker pull redis
 
sudo docker run --name product-test -d redis -p 6379:6379

Data Structures & Models

Strings

> SET user "Steve"
> GET user
"Steve"

Lists

  • Linked list.
> LPUSH users steve bob # add
> LINDEX users 0 # index
"steve"
> LRANGE users 0 -1 # range
"all list"

Sets

  • Mirip dengan list.
  • Tidak diambil dengan index dan unsorted.
  • unique.
> SADD fruit apple # add
> SMEMBERS fruit # list all member
"Apple"
> SISMEMBER fruit apple # if exist
1

Hashes

  • Menyimpan koleksi key:value.
> HSET house:5150 numBedrooms 3 squareFeet 2700 hvac "forced air"
> HGET house:5150 numBedrooms
"3"

Sorted Sets

  • Collection of unique elements with associated scores.
  • Range queries, leaderboards.
> ZADD userFollowers 31 steve 2 owen 13 jakob
> ZREVRANGE userFollowers 0 -1 WITHSCORES
"steve" 31
"jakob" 13
"owen" 2
> ZINCRBY userFollowers 20 jakob
"33"

HyperLogLog

  • menghitung estimasi unique items.
  • i.e. untuk tracking berapa banyak unique visitor di aplikasi.
> PFADD visitors 127.0.0.1

Pub/Sub

Pembuatan channel yang akan di-subscribe oleh client bisa menggunakan PUBLISH command.

> PUBLISH weather temp:85f
  1. SUBSCRIBE channel [channel ...]: Subscribes to one or more channels, where each channel is specified as a separate argument.
  2. UNSUBSCRIBE [channel [channel ...]]: Unsubscribes from one or more channels. If no channels are specified, the client is unsubscribed from all channels.
  3. PSUBSCRIBE pattern [pattern ...]: Subscribes to one or more channels using a pattern. For example, PSUBSCRIBE news.* would subscribe to all channels that start with “news.”.
  4. PUNSUBSCRIBE [pattern [pattern ...]]: Unsubscribes from one or more channels using a pattern.
  5. PUBLISH channel message: Publishes a message to a channel. All subscribers to that channel will receive the message.
# Open two separate Redis CLI sessions

# In the first session, subscribe to a channel
127.0.0.1:6379> SUBSCRIBE myChannel
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "myChannel"
3) (integer) 1

# In the second session, publish a message to the channel
127.0.0.1:6379> PUBLISH myChannel "Hello, world!"
(integer) 1

# Back in the first session, you should see the message printed to the console:
1) "message"
2) "myChannel"
3) "Hello, world!"