Introduction to Redis

  1. What Is Redis?



  2. Key Characteristics



  3. Installing Redis

  4. sudo zypper install redis
    
    sudo systemctl start redis
    sudo systemctl status redis
    sudo systemctl enable redis
    
    redis-cli ping
    PONG
    


  5. Connecting to Redis Using redis-cli

  6. redis-cli
    
    SET name "Alice"
    GET name
    DEL name
    


  7. Redis Data Types


  8. Type Description Examples
    String text, binary, counters SET key value
    List linked lists (queues) LPUSH jobs job1
    Set unordered unique elements SADD users alice
    Sorted Set ordered ranking (scores) ZADD leaderboard 100 user1
    Hash objects (like JSON) HSET user:1 name Alice age 20
    Bitmap efficient booleans SETBIT
    HyperLogLog estimate unique counts PFADD
    Streams distributed logs XADD


  9. Common Redis Use Cases



  10. Persistence in Redis



  11. Replication and High Availability



  12. Basic Commands You Should Know

  13. Category Commands
    Strings SET, GET, INCR, APPEND
    Lists LPUSH, RPUSH, LPOP
    Sets SADD, SMEMBERS
    Sorted Sets ZADD, ZRANGE
    Hashes HSET, HGETALL
    Keys DEL, EXPIRE, TTL
    Pub/Sub PUBLISH, SUBSCRIBE



Redis Commands Overview

  1. How Do Redis Commands Work?


  2. Key Management Commands


  3. Command Description Example
    SET key value Set key to hold the string value (overwrites any existing value). SET mykey "hello"
    GET key Get the value of key (or (nil) if not exists). GET mykey
    DEL key [key ...] Delete one or more keys; returns number of keys removed. DEL mykey otherkey
    EXISTS key [key ...] Return the number of keys that exist out of the given list. EXISTS mykey
    KEYS pattern Return all keys matching the pattern (use carefully in production). KEYS user:*
    SCAN cursor [MATCH pattern] [COUNT n] Incrementally iterate over keys (safer alternative to KEYS). SCAN 0 MATCH "user:*" COUNT 100
    EXPIRE key seconds Set a time-to-live (TTL) in seconds. EXPIRE session:123 3600
    TTL key Return remaining TTL in seconds (-1 = no TTL, -2 = key does not exist). TTL session:123
    RENAME key newkey Rename key to newkey (overwrites newkey if exists). RENAME user:1 user:001
    TYPE key Return the type of value stored at key (string, hash, list, set, zset, ...). TYPE user:1
    # Example: simple lifecycle of a key
    SET temp "value"
    EXPIRE temp 10
    TTL temp     # see remaining life
    GET temp     # value until it expires
    


  4. String Commands


  5. Command Description Example
    SET key value Set the string value of a key. SET page:home "<html>...</html>"
    GET key Get the value of a key. GET page:home
    SETNX key value Set key only if it does not already exist (NX = not exists). SETNX lock:job1 1
    INCR key Increment numeric value stored at key by 1 (creates key with value 0 if missing). INCR page:views
    INCRBY key increment Increment by a specified integer. INCRBY page:views 10
    DECR key, DECRBY Decrement integer value (symmetrical to INCR). DECR stock:widgets
    APPEND key value Append the string value to the existing value. APPEND log "error: something happened\n"
    MSET key value [key value ...] Set multiple keys at once. MSET user:1:name "Alice" user:1:age "30"
    MGET key [key ...] Get multiple keys at once. MGET user:1:name user:1:age
    # Example: a simple page view counter
    INCR page:/home
    INCR page:/home
    GET page:/home      # "2"


  6. Hash Commands


  7. Command Description Example
    HSET key field value Set field in hash to value (creates hash if missing). HSET user:1 name "Alice"
    HGET key field Get value of field in hash. HGET user:1 name
    HMSET key field value [field value ...] Set multiple fields in hash (deprecated, but still widely used; new: HSET with multiple field/value pairs). HSET user:1 name "Alice" age "30"
    HGETALL key Get all fields and values in the hash. HGETALL user:1
    HDEL key field [field ...] Delete one or more fields. HDEL user:1 age
    HLEN key Get number of fields in hash. HLEN user:1
    HEXISTS key field Check if field exists in hash. HEXISTS user:1 email
    # Example: storing a user as a hash
    HSET user:42 name "Alice" email "alice@example.com" age "30"
    HGET user:42 email
    HGETALL user:42


  8. List Commands


  9. Command Description Example
    LPUSH key value [value ...] Push value(s) to the left (head) of the list. LPUSH queue "job1"
    RPUSH key value [value ...] Push value(s) to the right (tail) of the list. RPUSH queue "job2"
    LPOP key, RPOP key Remove and return first/last element. LPOP queue
    LRANGE key start stop Get sub-list by index range (0-based, inclusive; -1 = last). LRANGE queue 0 -1
    LLEN key Get list length. LLEN queue
    BLPOP key [key ...] timeout Blocking pop from left; waits if list is empty. BLPOP queue 0
    # Example: simple FIFO queue
    RPUSH jobs "job1"
    RPUSH jobs "job2"
    LPOP jobs   # "job1"
    LPOP jobs   # "job2"


  10. Set Commands


  11. Command Description Example
    SADD key member [member ...] Add one or more members to the set. SADD tags "redis" "database"
    SMEMBERS key Get all set members. SMEMBERS tags
    SISMEMBER key member Check if member is in the set (returns 1 or 0). SISMEMBER tags "redis"
    SREM key member [member ...] Remove one or more members. SREM tags "database"
    SCARD key Count members of set. SCARD tags
    SINTER key [key ...] Set intersection of multiple sets. SINTER tags:post1 tags:post2
    SUNION key [key ...] Set union of multiple sets. SUNION tags:post1 tags:post3
    SDIFF key [key ...] Set difference. SDIFF tags:all tags:archived
    # Example: tracking unique visitors by day
    SADD visitors:2025-01-01 "user1"
    SADD visitors:2025-01-01 "user2"
    SCARD visitors:2025-01-01    # 2 unique visitors


  12. Sorted Set Commands (ZSET)


  13. Command Description Example
    ZADD key score member [score member ...] Add member(s) with scores to sorted set. ZADD leaderboard 100 "alice" 200 "bob"
    ZRANGE key start stop [WITHSCORES] Get elements by rank (ascending, 0 = lowest score). ZRANGE leaderboard 0 -1 WITHSCORES
    ZREVRANGE key start stop [WITHSCORES] Get elements by rank (descending, highest score first). ZREVRANGE leaderboard 0 9 WITHSCORES
    ZINCRBY key increment member Increment score of member by given amount. ZINCRBY leaderboard 50 "alice"
    ZREM key member [member ...] Remove member(s) from sorted set. ZREM leaderboard "alice"
    ZRANK key member, ZREVRANK Get rank of member (0-based). ZRANK leaderboard "alice"
    # Example: game leaderboard
    ZADD leaderboard 100 "alice"
    ZADD leaderboard 200 "bob"
    ZINCRBY leaderboard 50 "alice"   # alice now 150
    ZREVRANGE leaderboard 0 -1 WITHSCORES  # bob then alice


  14. Transactions and Pipelining
  15. # Example: a transaction
    MULTI
      INCR counter
      INCR counter
      GET counter
    EXEC

    # Pseudocode for WATCH usage
    WATCH balance:user:1
    current = GET balance:user:1
    if current >= 10:
        MULTI
          DECRBY balance:user:1 10
          INCRBY balance:store 10
        EXEC
    else:
        UNWATCH
    


  16. Publish/Subscribe Commands (Pub/Sub)


  17. Command Description Example
    SUBSCRIBE channel [channel ...] Subscribe to one or more channels. SUBSCRIBE news sports
    PUBLISH channel message Publish a message to a channel. PUBLISH news "breaking: ..."
    PSUBSCRIBE pattern [pattern ...] Subscribe to channels matching pattern. PSUBSCRIBE news.*
    # Terminal 1
    SUBSCRIBE chat
    
    # Terminal 2
    PUBLISH chat "hello world"


  18. Server & Introspection Commands


  19. Command Description Example
    INFO Show server statistics (memory, clients, keys, CPU, etc.). INFO
    DBSIZE Return number of keys in the current database. DBSIZE
    FLUSHDB Delete all keys in the current database. FLUSHDB
    FLUSHALL Delete all keys in all databases. FLUSHALL
    CONFIG GET pattern Get configuration parameters. CONFIG GET maxmemory
    CONFIG SET parameter value Change configuration at runtime. CONFIG SET maxmemory 512mb


  20. Putting It All Together: Small Example Application

  21. # 1) Create user profile
    HSET user:100 name "Alice" email "alice@example.com"
    
    # 2) Increase login counter
    INCR user:100:logins
    
    # 3) Add an action to the activity list (keep last 50)
    LPUSH user:100:actions "logged_in"
    LTRIM user:100:actions 0 49
    
    # 4) Update score in leaderboard
    ZINCRBY leaderboard 10 "user:100"
    
    # 5) Show top 3 users
    ZREVRANGE leaderboard 0 2 WITHSCORES