forked from julien-duponchelle/python-mysql-replication
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmysql_to_rabbitmq.py
67 lines (52 loc) · 2.07 KB
/
mysql_to_rabbitmq.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
#
# Update a RabbitMQ when an event is triggered
# in MySQL replication log
#
import json
import pika
from pika import DeliveryMode
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import (
DeleteRowsEvent,
UpdateRowsEvent,
WriteRowsEvent,
)
MYSQL_SETTINGS = {"host": "127.0.0.1", "port": 3306, "user": "root",
"passwd": "password"}
def main():
stream = BinLogStreamReader(
connection_settings=MYSQL_SETTINGS,
server_id=3,
only_events=[DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent],
)
credentials = pika.PlainCredentials(
username='username',
password='password'
)
params = pika.ConnectionParameters('rabbitmq_host', credentials=credentials)
# RabbitMQ Connection Settings
conn = pika.BlockingConnection(params)
channel = conn.channel()
channel.queue_declare(queue='order')
channel.exchange_declare(durable=True, exchange_type='direct', exchange='direct')
channel.queue_bind(queue='order', exchange='direct', routing_key='order')
for binlogevent in stream:
for row in binlogevent.rows:
if isinstance(binlogevent, DeleteRowsEvent):
routing_key = "order"
message_body = row["values"].items()
elif isinstance(binlogevent, UpdateRowsEvent):
routing_key = "order"
message_body = row["after_values"].items()
elif isinstance(binlogevent, WriteRowsEvent):
routing_key = "order"
message_body = row["values"].items()
properties = pika.BasicProperties(content_type='application/json',
delivery_mode=DeliveryMode.Transient)
channel.basic_publish(exchange='direct', routing_key=routing_key,
body=json.dumps(dict(message_body)), properties=properties)
stream.close()
conn.close()
if __name__ == '__main__':
main()