ClientSample

直接使用canal.example工程

a. 首先启动Canal Server,可参见QuickStartb.

  • 可以在eclipse里,直接打开com.alibaba.otter.canal.example.SimpleCanalClientTest,直接运行
  • 在工程的example目录下运行命令行:
    mvn exec:java -Dexec.mainClass="com.alibaba.otter.canal.example.SimpleCanalClientTest"

  • 下载example包: https://github.com/alibaba/canal/releases,解压缩后,直接运行sh 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.0.12</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
  1. 修改pom.xml,添加依赖
  1. ClientSample代码
  1. package com.alibaba.otter.canal.sample;
  2.  
  3. import java.net.InetSocketAddress;
  4. import java.util.List;
  5.  
  6.  
  7. import com.alibaba.otter.canal.client.CanalConnectors;
  8. import com.alibaba.otter.canal.client.CanalConnector;
  9. import com.alibaba.otter.canal.common.utils.AddressUtils;
  10. import com.alibaba.otter.canal.protocol.Message;
  11. import com.alibaba.otter.canal.protocol.CanalEntry.Column;
  12. import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
  13. import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;
  14. import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
  15. import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
  16. import com.alibaba.otter.canal.protocol.CanalEntry.RowData;
  17.  
  18.  
  19. public class SimpleCanalClientExample {
  20.  
  21.  
  22. public static void main(String args[]) {
  23.     // 创建链接
  24.     CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress(AddressUtils.getHostIp(),
  25.                                                                                         11111), "example", "", "");
  26.     int batchSize = 1000;
  27.     int emptyCount = 0;
  28.     try {
  29.         connector.connect();
  30.         connector.subscribe(".*\\..*");
  31.         connector.rollback();
  32.         int totalEmptyCount = 120;
  33.         while (emptyCount < totalEmptyCount) {
  34.             Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据
  35.             long batchId = message.getId();
  36.             int size = message.getEntries().size();
  37.             if (batchId == -1 || size == 0) {
  38.                 emptyCount++;
  39.                 System.out.println("empty count : " + emptyCount);
  40.                 try {
  41.                     Thread.sleep(1000);
  42.                 } catch (InterruptedException e) {
  43.                 }
  44.             } else {
  45.                 emptyCount = 0;
  46.                 // System.out.printf("message[batchId=%s,size=%s] \n", batchId, size);
  47.                 printEntry(message.getEntries());
  48.             }
  49.             connector.ack(batchId); // 提交确认
  50.             // connector.rollback(batchId); // 处理失败, 回滚数据
  51.         }
  52.         System.out.println("empty too many times, exit");
  53.     } finally {
  54.         connector.disconnect();
  55.     }
  56. }
  57. private static void printEntry(List<Entry> entrys) {
  58.     for (Entry entry : entrys) {
  59.         if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) {
  60.             continue;
  61.         }
  62.         RowChange rowChage = null;
  63.         try {
  64.             rowChage = RowChange.parseFrom(entry.getStoreValue());
  65.         } catch (Exception e) {
  66.             throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(),
  67.                                        e);
  68.         }
  69.         EventType eventType = rowChage.getEventType();
  70.         System.out.println(String.format("================&gt; binlog[%s:%s] , name[%s,%s] , eventType : %s",
  71.                                          entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
  72.                                          entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
  73.                                          eventType));
  74.         for (RowData rowData : rowChage.getRowDatasList()) {
  75.             if (eventType == EventType.DELETE) {
  76.                 printColumn(rowData.getBeforeColumnsList());
  77.             } else if (eventType == EventType.INSERT) {
  78.                 printColumn(rowData.getAfterColumnsList());
  79.             } else {
  80.                 System.out.println("-------&gt; before");
  81.                 printColumn(rowData.getBeforeColumnsList());
  82.                 System.out.println("-------&gt; after");
  83.                 printColumn(rowData.getAfterColumnsList());
  84.             }
  85.         }
  86.     }
  87. }
  88. private static void printColumn(List<Column> columns) {
  89.     for (Column column : columns) {
  90.         System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
  91.     }
  92. }
  93.  
  94.  
  95.  
  96. }

  1. 运行Client

首先启动Canal Server,可参见QuickStart

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

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

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

  1. 触发数据库变更
  1. mysql> use test;
  2. Database changed
  3. mysql> CREATE TABLE `xdual` (
  4. -> `ID` int(11) NOT NULL AUTO_INCREMENT,
  5. -> `X` 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.  
  10. 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工程,谢谢.

原文: https://github.com/alibaba/canal/wiki/ClientExample