ClientSample

    a. 首先启动Canal Server,可参见[[QuickStart]]
    b.

    1. 在工程的example目录下运行命令行:

    2. 下载example包: startup.sh脚本
    c. 触发数据变更 d. 在控制台或者logs中查看,可以看到如下信息 :

    1. ================> binlog[mysql-bin.002579:508882822] , name[retl,xdual] , eventType : UPDATE , executeTime : 1368607728000 , delay : 4270ms
    2. ———-> before
    3. ID : 1 update=false
    4. X : 2013-05-15 11:43:42 update=false
    5. ———-> after
    6. ID : 1 update=false
    7. X : 2013-05-15 16:48:48 update=true


    依赖配置:

    1. <dependency>
    2. <groupId>com.alibaba.otter</groupId>
    3. <artifactId>canal.client</artifactId>
    4. <version>1.1.0</version>
    5. </dependency>

    1. 创建mvn标准工程:

    1. mvn archetype:create -DgroupId=com.alibaba.otter -DartifactId=canal.sample
    maven3.0.5以上版本舍弃了create,使用generate生成项目

    1. mvn archetype:generate -DgroupId=com.alibaba.otter -DartifactId=canal.sample

    3. ClientSample代码

    1. package com.alibaba.otter.canal.sample;

    2. import java.net.InetSocketAddress;

    3. import java.util.List;

    4. import com.alibaba.otter.canal.client.CanalConnectors;

    5. import com.alibaba.otter.canal.client.CanalConnector;

    6. import com.alibaba.otter.canal.common.utils.AddressUtils;

    7. import com.alibaba.otter.canal.protocol.Message;

    8. import com.alibaba.otter.canal.protocol.CanalEntry.Column;

    9. import com.alibaba.otter.canal.protocol.CanalEntry.Entry;

    10. import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;

    11. import com.alibaba.otter.canal.protocol.CanalEntry.EventType;

    12. import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;

    13. import com.alibaba.otter.canal.protocol.CanalEntry.RowData;

    14. public class SimpleCanalClientExample {

    15.     // 创建链接
    16.     CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(AddressUtils.getHostIp(),
    17.                                                                                         11111), "example", "", "");
    18.     int batchSize = 1000;
    19.     int emptyCount = 0;
    20.     try {
    21.         connector.connect();
    22.         connector.subscribe(".*\\..*");
    23.         connector.rollback();
    24.         int totalEmptyCount = 120;
    25.         while (emptyCount < totalEmptyCount) {
    26.             Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
    27.             int size = message.getEntries().size();
    28.             if (batchId == -1 || size == 0) {
    29.                 emptyCount++;
    30.                 System.out.println("empty count : " + emptyCount);
    31.                 try {
    32.                     Thread.sleep(1000);
    33.                 } catch (InterruptedException e) {
    34.                 }
    35.             } else {
    36.                 // System.out.printf("message[batchId=%s,size=%s] \n", batchId, size);
    37.                 printEntry(message.getEntries());
    38.             }
    39.             connector.ack(batchId); // 提交确认
    40.             // connector.rollback(batchId); // 处理失败, 回滚数据
    41.         }
    42.         System.out.println("empty too many times, exit");
    43.     } finally {
    44.         connector.disconnect();
    45.     }
    46. }
    47. private static void printEntry(List<Entry> entrys) {
    48.     for (Entry entry : entrys) {
    49.         if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
    50.             continue;
    51.         }
    52.         RowChange rowChage = null;
    53.         try {
    54.             rowChage = RowChange.parseFrom(entry.getStoreValue());
    55.         } catch (Exception e) {
    56.             throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
    57.                                        e);
    58.         }
    59.         System.out.println(String.format("================&gt; binlog[%s:%s] , name[%s,%s] , eventType : %s",
    60.                                          entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
    61.                                          eventType));
    62.         for (RowData rowData : rowChage.getRowDatasList()) {
    63.             if (eventType == EventType.DELETE) {
    64.                 printColumn(rowData.getBeforeColumnsList());
    65.             } else if (eventType == EventType.INSERT) {
    66.                 printColumn(rowData.getAfterColumnsList());
    67.             } else {
    68.                 System.out.println("-------&gt; before");
    69.                 printColumn(rowData.getBeforeColumnsList());
    70.                 System.out.println("-------&gt; after");
    71.                 printColumn(rowData.getAfterColumnsList());
    72.             }
    73.         }
    74.     }
    75. }
    76. private static void printColumn(List<Column> columns) {
    77.     for (Column column : columns) {
    78.         System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
    79.     }
    80. }
    81. }

    4. 运行Client

    首先启动Canal Server,可参见[[QuickStart]]

    启动Canal Client后,可以从控制台从看到类似消息:

    1. empty count : 1
    2. empty count : 2
    3. empty count : 3
    4. empty count : 4

    此时代表当前数据库无变更数据

    5. 触发数据库变更

    1. mysql> use test;
    2. Database changed
    3. mysql> CREATE TABLE xdual (
    4. -> ID int(11) NOT NULL AUTO_INCREMENT,
    5. -> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    6. -> PRIMARY KEY (ID)
    7. -> ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 ;
    8. Query OK, 0 rows affected (0.06 sec)

    9. mysql> insert into xdual(id,x) values(null,now());Query OK, 1 row affected (0.06 sec)

    可以从控制台中看到:

    1. empty count : 1
    2. empty count : 2
    3. empty count : 3
    4. empty count : 4
    5. ================> binlog[mysql-bin.001946:313661577] , name[test,xdual] , eventType : INSERT
    6. ID : 4 update=true
    7. X : 2013-02-05 23:29:46 update=true

    如果需要更详细的exmpale例子,请下载canal当前最新源码包,里面有个example工程,谢谢.