Skip to content

Commit e5820ce

Browse files
committed
add new api with opcode for notification of redis DB
1 parent cb4fec9 commit e5820ce

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/swsssdk/configdb.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,32 @@ def listen(self):
9898
except ValueError:
9999
pass #Ignore non table-formated redis entries
100100

101+
def __fire_with_op(self, table, key, data, op_str='add'):
102+
if self.handlers.has_key(table):
103+
handler = self.handlers[table]
104+
handler(table, key, data, op_str)
105+
106+
def listen_with_op(self):
107+
"""Start listen Redis keyspace events and will trigger corresponding handlers when content of a table changes.
108+
"""
109+
self.pubsub = self.redis_clients[self.CONFIG_DB].pubsub()
110+
self.pubsub.psubscribe("__keyspace@{}__:*".format(self.db_map[self.CONFIG_DB]['db']))
111+
for item in self.pubsub.listen():
112+
if item['type'] == 'pmessage':
113+
key = item['channel'].split(':', 1)[1]
114+
try:
115+
(table, row) = key.split(self.TABLE_NAME_SEPARATOR, 1)
116+
if self.handlers.has_key(table):
117+
client = self.redis_clients[self.CONFIG_DB]
118+
data = self.__raw_to_typed(client.hgetall(key))
119+
op = client.keys(key)
120+
op_str = 'add'
121+
if len(op) == 0:
122+
op_str = 'del'
123+
self.__fire_with_op(table, row, data, op_str)
124+
except ValueError:
125+
pass #Ignore non table-formated redis entries
126+
101127
def __raw_to_typed(self, raw_data):
102128
if raw_data == None:
103129
return None

0 commit comments

Comments
 (0)