canal能夠用來監控數據庫數據的變化,從而得到新增數據,或者修改的數據,用於實際工做中,比較實用,特此記錄一下html
canal是應阿里巴巴存在杭州和美國的雙機房部署,存在跨機房同步的業務需求而提出的。java
阿里系公司開始逐步的嘗試基於數據庫的日誌解析,獲取增量變動進行同步,由此衍生出了增量訂閱&消費的業務mysql
基於日誌增量訂閱&消費支持的業務:
數據庫鏡像
數據庫實時備份
多級索引 (賣家和買家各自分庫索引)
search build
業務cache刷新
價格變化等重要業務消息git
keyword:數據庫同步,增量訂閱&消費。github
https://github.com/alibaba/canal/releasessql
在opt下(或者其餘目錄)建立一個canal文件夾數據庫
由於canal解壓後並無總體的文件夾,是把裏面的內容一下解壓出來的ide
而後進入canal文件夾,將安裝包canal.deployer-1.0.24.tar.gz傳輸進來函數
解壓:ui
tar -zxvf canal.deployer-1.0.24.tar.gz
能夠刪除安裝包canal.deployer-1.0.24.tar.gz了
vi conf/example/instance.properties
修改紅框內的內容
canal.instance.dbUsername = **** #數據庫用戶名
canal.instance.dbPassword = **** #數據庫密碼
canal.instance.defaultDatabaseName = **** #指定須要同步的數據庫
canal.instance.connectionCharset = UTF-8 #指定編碼方式
而後保存:
esc
:wq
vi /etc/my.cnf
添加如下三行內容,若是原來存在,則不須要添加,只需對當前配置項進行修改便可
log-bin=mysql-bin #添加這一行就ok
binlog-format=ROW #選擇row模式
server-id=1 #配置mysql replaction須要定義,不能和canal的slaveId重複
而後保存:
esc
:wq
用root用戶登陸mysql:
mysql -uroot -p
回車,輸入密碼
建立「canal」用戶:
create user canal identified by 'canal';
有可能會出現以下狀況:
直接刷新:
FLUSH PRIVILEGES;
而後再次建立「canal」用戶
爲「canal」用戶賦予相應權限:
GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'canal'@'%';
而後刷新權限:
FLUSH PRIVILEGES;
退出mysql
exit;
sudo service mysqld restart
cd到bin目錄,啓動canal-server
cd bin/ ./startup.sh
查看啓動狀態:
tail -f -n 50 ../logs/canal/canal.log
package com.test; import java.net.InetSocketAddress; import java.util.List; import com.alibaba.otter.canal.client.CanalConnector; import com.alibaba.otter.canal.client.CanalConnectors; import com.alibaba.otter.canal.protocol.CanalEntry.Column; import com.alibaba.otter.canal.protocol.CanalEntry.Entry; import com.alibaba.otter.canal.protocol.CanalEntry.EntryType; import com.alibaba.otter.canal.protocol.CanalEntry.EventType; import com.alibaba.otter.canal.protocol.CanalEntry.RowChange; import com.alibaba.otter.canal.protocol.CanalEntry.RowData; import com.alibaba.otter.canal.protocol.Message; public class TestCanal { public static void main(String args[]) { // 建立連接 CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("***canal所在的主機ip***", 11111), "example", "", ""); int batchSize = 1000; int emptyCount = 0; try { connector.connect(); connector.subscribe(".*\\..*"); connector.rollback(); int totalEmtryCount = 1200; while (emptyCount < totalEmtryCount) { Message message = connector.getWithoutAck(batchSize); // 獲取指定數量的數據 long batchId = message.getId(); int size = message.getEntries().size(); if (batchId == -1 || size == 0) { emptyCount++; // System.out.println("empty count : " + emptyCount); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } else { emptyCount = 0; // System.out.printf("message[batchId=%s,size=%s] \n", batchId, size); printEntry(message.getEntries()); } connector.ack(batchId); // 提交確認 // connector.rollback(batchId); // 處理失敗, 回滾數據 } System.out.println("empty too many times, exit"); } finally { connector.disconnect(); } } private static void printEntry(List<Entry> entrys) { for (Entry entry : entrys) { if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) { continue; } RowChange rowChage = null; try { rowChage = RowChange.parseFrom(entry.getStoreValue()); } catch (Exception e) { throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e); } EventType eventType = rowChage.getEventType(); System.out.println(String.format("================> binlog[%s:%s] , name[%s,%s] , eventType : %s", entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(), entry.getHeader().getSchemaName(), entry.getHeader().getTableName(), eventType)); for (RowData rowData : rowChage.getRowDatasList()) { if (eventType == EventType.DELETE) { printColumn(rowData.getBeforeColumnsList()); } else if (eventType == EventType.INSERT) { printColumn(rowData.getAfterColumnsList()); } else { System.out.println("-------> before"); printColumn(rowData.getBeforeColumnsList()); System.out.println("-------> after"); printColumn(rowData.getAfterColumnsList()); } } } } private static void printColumn(List<Column> columns) { for (Column column : columns) { System.out.println(column.getName() + " : " + column.getValue() + " update=" + column.getUpdated()); } } }
直接啓動mian函數
而後任意選擇一張表,插入數據庫一條數據
控制檯輸出內容
更多信息能夠參考:
談談對Canal( 增量數據訂閱與消費 )的理解
http://www.importnew.com/25189.html
https://blog.csdn.net/my201110lc/article/details/78836270