如何通過實時更新獲取數(shù)據(jù)庫新增數(shù)據(jù)
問題:
用戶需要及時獲取 mysql 表中的新增數(shù)據(jù),以便通過短信發(fā)送給指定號碼。傳統(tǒng)的方法是通過服務(wù)器計劃任務(wù)每 30 秒讀取數(shù)據(jù)庫,但這會增加服務(wù)器負擔(dān)并延遲獲取數(shù)據(jù)。
解決方案:
使用 MySQL Binary Log (Binlog) 和 Canal
-
打開 MySQL 的 Binlog:
- 在 my.cnf 文件中,找到 binlog-do-db 和 binlog-ignore-db 選項,并將其設(shè)置為指定要記錄的數(shù)據(jù)庫。
- 確保 Binlog 已打開,并通過 SHOW MASTER LOGS 命令驗證。
-
安裝 Canal:
- Canal 是一個開源組件,用于訂閱 MySQL 的 Binlog。
- 在服務(wù)器上安裝 Canal,并按照其文檔進行配置。
-
配置 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 (要訂閱的表名稱)
-
-
啟動 Canal 服務(wù):
- 運行 sh bin/startup.sh 命令啟動 Canal。
-
實現(xiàn) php 監(jiān)聽器:
通過上述方法,可以實現(xiàn)實時獲取數(shù)據(jù)庫新增數(shù)據(jù)的需求,無需使用計劃任務(wù),并且可以減少服務(wù)器負擔(dān)。