Skip to content

Instantly share code, notes, and snippets.

@riking
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riking/956e8f0e6bdfa927a089 to your computer and use it in GitHub Desktop.
Save riking/956e8f0e6bdfa927a089 to your computer and use it in GitHub Desktop.
MAX_MESSAGES = 20
# @author Kane York (@riking)
# @license BSD 2-clause
class SaveChatMessages:
def __init__(self):
self._redis = None
def on_redis_reconnect(self, redis):
"""
This method must be called every time the Redis connection is started or restarted.
"""
self._redis = redis
self._init_redis()
def _init_redis(self):
"""
Loads the chat message saving Lua script into the Redis cache.
"""
script = """
local count
count = redis.call("LLEN", KEYS[1])
if count < %d
redis.call("LPUSH", KEYS[1], ARGV[1])
else
redis.call("RPOPLPUSH", KEYS[1], ARGV[1])
end
redis.call("EXPIRE", KEYS[1], 60 * 30) -- 30 minutes
""" % (MAX_MESSAGES,)
self._script_hash = sha.new(script).hexdigest()
self._redis.SCRIPTLOAD(script)
def saveChatMessage(self, channel, message_json):
"""
Save a single chat message to the Redis server.
"""
self._redis.EVALSHA(self._script_hash, 1, channel, message_json)
def getRecentChatMessages(self, channel):
"""
Get the recent chat messages from the Redis server.
Returns a list of JSON objects, from oldest to newest.
"""
# should LRU cache this as well
# don't forget cache invalidation in saveChatMessage()
ary = self._redis.LRANGE(channel, 0, (MAX_MESSAGES - 1))
ary.reverse()
return ary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment