Last active
August 29, 2015 14:22
-
-
Save riking/956e8f0e6bdfa927a089 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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