REDIS

Ales Zoulek (@aleszoulek) | <ales.zoulek@gmail.com>images/redis-300dpi.png

"Simplicity is the ultimate sophistication."

-- Leonardo Da Vinci

Description

Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

Key value

Use cases

Use case - Pagination

class Pagination(object):

  # len(pagination_homepage))
  def __len__(self):
    redis.zcard(self.get_key())

  # pagination_homepage[10:20]
  def __getitem__(self, k):
      return db.get_by_pk(
        redis.zrevrangebyscore(
          self.get_key(),  # pagination_homepage
          time.time(), 0,  # now() - 0
          k.start, k.stop, # 10 - 20
        )
      )

Use case - Queue

# publisher:
redis.rpush(QUEUE_NAME, task)

# worker:
while True:
  task = redis.blpop(QUEUE_NAME)
  do_something(task)

Use case - Cache

slaveof redis-master.example.com 9000

Use case - Chat 1/2

def publish(message):
    action_time = time.time()
    # run all redis queries in a pipe
    pipe = redis.pipeline()
    # add the actions to the master zset
    pipe = pipe.zadd(ACTIONS_KEY, message, action_time)
    # trim the zset to only contain 30 actions
    pipe = pipe.zremrangebyrank(ACTIONS_KEY, 0, -31)
    # execute everything at once
    pipe.execute()
    # publish to all clients waiting for a message
    redis.publish(BROADCAST_KEY, message)

Use case - Chat 2/2

def poll(last_seen):
    # last_seen - retrieve only new actions
    actions = redis.zrangebyscore(ACTIONS_KEY,
      min='(%f' % last_seen, max=time.time(), withscores=True)
    if actions:
        return actions

    # no new actions stored in redis, wait for them
    pubsub = redis.pubsub()
    pubsub.subscribe(BROADCAST_KEY)
    try:
        message = pubsub.listen().next():
    except ConnectionError: # timeout
        return []
    else:
        return [message]
    finally:
        pubsub.unsubscribe()

Next time

Questions

????