canal記錄

當咱們須要對數據庫的修改作監聽的時候,能夠使用阿里的canal。例如,能夠實現將mysql中修改的數據更新到redis中,而不用每一個service都分兩步去先操做mysql再操做redis。java

配置mysql

啓用mysql的binlog

# vim /etc/my.cnf

添加:
[mysqld]  
log-bin=mysql-bin #添加這一行就ok  
binlog-format=ROW #選擇row模式  
server_id=1 #配置mysql replaction須要定義,不能和canal的slaveId重複

添加canal數據庫用戶

CREATE USER canal IDENTIFIED BY 'canal';      
GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'canal'@'%';    
-- GRANT ALL PRIVILEGES ON *.* TO 'canal'@'%' ;    
FLUSH PRIVILEGES;

配置canal

解壓

mkdir /tmp/canal  
tar zxvf canal.deployer-$version.tar.gz  -C /tmp/canal

修改配置文件

vi conf/example/instance.properties  
#################################################  
## mysql serverId  
canal.instance.mysql.slaveId = 1234  
  
# position info,須要改爲本身的數據庫信息  
canal.instance.master.address = 127.0.0.1:3306   
canal.instance.master.journal.name =   
canal.instance.master.position =   
canal.instance.master.timestamp =   
  
#canal.instance.standby.address =   
#canal.instance.standby.journal.name =  
#canal.instance.standby.position =   
#canal.instance.standby.timestamp =   
  
# username/password,須要改爲本身的數據庫信息  
canal.instance.dbUsername = canal    
canal.instance.dbPassword = canal  
canal.instance.defaultDatabaseName =  
canal.instance.connectionCharset = UTF-8  
  
# table regex  
canal.instance.filter.regex = .*\\..*  
  
#################################################

啓動

sh bin/startup.sh
public class ClientSample {
  
    public static void main(String args[]) {  
        // 建立連接  
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("10.0.0.2",
                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());
                    //redisDelete(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());
        }  
    }  
}

注意

canal每次會記錄客戶端消費的位置。若是canal掛掉,mysql在不斷更新,redis更新滯後。重啓canal後,會自動同步redis更新。mysql

HA

server端可參考官方文檔git

client也是靠zookeeper實現hagithub

CanalConnector connector = CanalConnectors.newClusterConnector("192.168.213.44:4180", "example", "", "");  //client鏈接zookeeper地址
  
        int batchSize = 1;  
        int emptyCount = 0;  
        //啓動多個實例,不斷嘗試鏈接zookeeper實現HA。
        while(true) {  
            try {  
                connector.connect();  
                connector.subscribe(".*\\..*");  
                ...
        }

Reference

相關文章
相關標籤/搜索