如何通過實(shí)時(shí)更新獲取數(shù)據(jù)庫新增數(shù)據(jù)
問題:
用戶需要及時(shí)獲取 mysql 表中的新增數(shù)據(jù),以便通過短信發(fā)送給指定號(hào)碼。傳統(tǒng)的方法是通過服務(wù)器計(jì)劃任務(wù)每 30 秒讀取數(shù)據(jù)庫,但這會(huì)增加服務(wù)器負(fù)擔(dān)并延遲獲取數(shù)據(jù)。
解決方案:
使用 MySQL Binary Log (Binlog) 和 Canal
-
打開 MySQL 的 Binlog:
- 在 my.cnf 文件中,找到 binlog-do-db 和 binlog-ignore-db 選項(xiàng),并將其設(shè)置為指定要記錄的數(shù)據(jù)庫。
- 確保 Binlog 已打開,并通過 SHOW MASTER LOGS 命令驗(yàn)證。
-
安裝 Canal:
- Canal 是一個(gè)開源組件,用于訂閱 MySQL 的 Binlog。
- 在服務(wù)器上安裝 Canal,并按照其文檔進(jìn)行配置。
-
配置 Canal 訂閱 Binlog:
-
打開 Canal 的配置文件 canal.properties,并配置以下內(nèi)容:
- canal.destinations=example
- canal.app.destination.example.dw.dbAddress=localhost (數(shù)據(jù)庫地址)
- canal.app.destination.example.dw.dbPort=3306 (數(shù)據(jù)庫端口)
- canal.app.destination.example.dw.dbUsername=root (數(shù)據(jù)庫用戶名)
- canal.app.destination.example.dw.dbPassword=password (數(shù)據(jù)庫密碼)
- canal.app.destination.example.dw.database=mysql (要訂閱的數(shù)據(jù)庫名稱)
- canal.app.destination.example.dw.table=tbl_name (要訂閱的表名稱)
-
-
啟動(dòng) Canal 服務(wù):
- 運(yùn)行 sh bin/startup.sh 命令啟動(dòng) Canal。
-
實(shí)現(xiàn) php 監(jiān)聽器:
通過上述方法,可以實(shí)現(xiàn)實(shí)時(shí)獲取數(shù)據(jù)庫新增數(shù)據(jù)的需求,無需使用計(jì)劃任務(wù),并且可以減少服務(wù)器負(fù)擔(dān)。