-
Notifications
You must be signed in to change notification settings - Fork 682
/
Copy pathredis_cache.py
50 lines (38 loc) · 1.3 KB
/
redis_cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python
#
# Update a redis server cache when an evenement is trigger
# in MySQL replication log
#
import redis
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (
DeleteRowsEvent,
UpdateRowsEvent,
WriteRowsEvent,
)
MYSQL_SETTINGS = {"host": "127.0.0.1", "port": 3306, "user": "root", "passwd": ""}
def main():
r = redis.Redis()
stream = BinLogStreamReader(
connection_settings=MYSQL_SETTINGS,
server_id=3, # server_id is your slave identifier, it should be unique
only_events=[DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent],
)
for binlogevent in stream:
prefix = (
f"{binlogevent.schema}:"
f"{binlogevent.table}:"
)
for row in binlogevent.rows:
if isinstance(binlogevent, DeleteRowsEvent):
vals = row["values"]
r.delete(prefix + str(vals["id"]))
elif isinstance(binlogevent, UpdateRowsEvent):
vals = row["after_values"]
r.hmset(prefix + str(vals["id"]), vals)
elif isinstance(binlogevent, WriteRowsEvent):
vals = row["values"]
r.hmset(prefix + str(vals["id"]), vals)
stream.close()
if __name__ == "__main__":
main()