ClientSample

直接使用canal.example工程

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

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

  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. 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工程,谢谢.