导包

  1. <!-- https://mvnrepository.com/artifact/com.alibaba.otter/canal.client -->
  2. <dependency>
  3. <groupId>com.alibaba.otter</groupId>
  4. <artifactId>canal.client</artifactId>
  5. <version>1.1.0</version>
  6. </dependency>
  7. <!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients -->
  8. <dependency>
  9. <groupId>org.apache.kafka</groupId>
  10. <artifactId>kafka-clients</artifactId>
  11. <version>3.1.0</version>
  12. </dependency>

例子

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.alibaba.otter.canal.client.CanalConnector;
  3. import com.alibaba.otter.canal.client.CanalConnectors;
  4. import com.alibaba.otter.canal.protocol.CanalEntry;
  5. import com.alibaba.otter.canal.protocol.Message;
  6. import com.google.protobuf.ByteString;
  7. import com.google.protobuf.InvalidProtocolBufferException;
  8. import java.net.InetSocketAddress;
  9. import java.util.List;
  10. public class CanalClient {
  11. public static void main(String[] args) {
  12. // 获取连接
  13. // 这里填写canal所配置的服务器ip,端口号,destination(在canal.properties文件里)以及服务器账号密码
  14. CanalConnector canalConnector = CanalConnectors.newSingleConnector(
  15. new InetSocketAddress("127.0.0.1", 11111),
  16. "example", "", "");
  17. try {
  18. // 打开连接
  19. canalConnector.connect();
  20. // 订阅数据库 gamll 库的 所有表
  21. canalConnector.subscribe("gmall\\..*");// .*代表database,..*代表table
  22. //订阅数据库表,全部表
  23. // canalConnector.subscribe(".*\\..*");
  24. //回滚到未进行ack的地方,下次fetch的时候,可以从最后一个没有ack的地方开始拿
  25. canalConnector.rollback();
  26. while (true) {
  27. // 获取指定数量 数据
  28. Message message = canalConnector.getWithoutAck(100);
  29. // Message message = canalConnector.get(100);
  30. //获取批量ID
  31. long batchId = message.getId();
  32. // 获取Entry集合 数量
  33. List<CanalEntry.Entry> entries = message.getEntries();
  34. // 判断集合是否为空,如果为空,则等待一会继续拉取数据
  35. if (batchId == -1 || entries.size() <= 0) {
  36. System.out.println("当前抓取没有数据,休息一会。。。。。。");
  37. Thread.sleep(10000);
  38. } else {
  39. // 遍历entries,单条解析
  40. printEntry(entries);
  41. }
  42. //进行 batch id 的确认。确认之后,小于等于此 batchId 的 Message 都会被确认。
  43. canalConnector.ack(batchId);
  44. // canalConnector.rollback(batchId); // 处理失败, 回滚数据
  45. }
  46. } catch (Throwable e) {
  47. e.printStackTrace();
  48. } finally {
  49. canalConnector.disconnect();
  50. }
  51. }
  52. /**
  53. * 打印canal server解析binlog获得的实体类信息
  54. */
  55. private static void printEntry(List<CanalEntry.Entry> entries) throws InvalidProtocolBufferException {
  56. for (CanalEntry.Entry entry : entries) {
  57. //1.获取表名
  58. String tableName = entry.getHeader().getTableName();
  59. //2.获取类型
  60. CanalEntry.EntryType entryType = entry.getEntryType();
  61. if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
  62. //开启/关闭事务的实体类型,跳过
  63. continue;
  64. }
  65. //3.获取序列化后的数据
  66. ByteString storeValue = entry.getStoreValue();
  67. //4.判断当前entryType类型是否为ROWDATA
  68. if (CanalEntry.EntryType.ROWDATA.equals(entryType)) {
  69. //5.反序列化数据
  70. //RowChange对象,包含了一行数据变化的所有特征
  71. //比如isDdl 是否是ddl变更操作 sql 具体的ddl sql beforeColumns afterColumns 变更前后的数据字段等等
  72. CanalEntry.RowChange rowChange;
  73. try {
  74. rowChange = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
  75. } catch (Throwable e) {
  76. throw new RuntimeException("ERROR ## canal解析出错, data:" + entry.toString(), e);
  77. }
  78. //6.获取当前事件的操作类型, insert/update/delete类型
  79. CanalEntry.EventType eventType = rowChange.getEventType();
  80. //打印Header信息
  81. System.out.println(String.format("================》; binlog[%s:%s] , name[%s,%s] , eventType : %s",
  82. entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
  83. entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
  84. eventType));
  85. //判断是否是DDL语句
  86. if (rowChange.getIsDdl()) {
  87. System.out.println("================》;isDDl: true,sql:" + rowChange.getSql());
  88. }
  89. //7.获取数据集
  90. List<CanalEntry.RowData> rowDataList = rowChange.getRowDatasList();
  91. //8.遍历rowDataList,并打印数据集
  92. for (CanalEntry.RowData rowData : rowDataList) {
  93. // 判断类型
  94. // eventType == CanalEntry.EventType.DELETE
  95. //如果是删除语句
  96. // if (eventType == CanalEntry.EventType.DELETE) {
  97. // printColumn(rowData.getBeforeColumnsList());
  98. // //如果是新增语句
  99. // } else if (eventType == CanalEntry.EventType.INSERT) {
  100. // printColumn(rowData.getAfterColumnsList());
  101. // //如果是更新的语句
  102. // } else {
  103. // //变更前的数据
  104. // System.out.println("------->; before");
  105. // printColumn(rowData.getBeforeColumnsList());
  106. // //变更后的数据
  107. // System.out.println("------->; after");
  108. // printColumn(rowData.getAfterColumnsList());
  109. // }
  110. JSONObject beforeData = new JSONObject();
  111. List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
  112. for (CanalEntry.Column column : beforeColumnsList) {
  113. beforeData.put(column.getName(), column.getValue());
  114. }
  115. JSONObject afterData = new JSONObject();
  116. List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
  117. for (CanalEntry.Column column : afterColumnsList) {
  118. afterData.put(column.getName(), column.getValue());
  119. }
  120. //数据打印
  121. System.out.println("Table:" + tableName + System.lineSeparator() +
  122. "EventType:" + eventType + System.lineSeparator() +
  123. "之前数据是:" + beforeData + System.lineSeparator() +
  124. "之后数据是:" + afterData);
  125. }
  126. } else {
  127. System.out.println("当前操作类型为:" + entryType);
  128. }
  129. }
  130. }
  131. private static void printColumn(List<CanalEntry.Column> columns) {
  132. for (CanalEntry.Column column : columns) {
  133. System.out.println(column.getName() + " : " + column.getValue() + " update=" + column.getUpdated());
  134. }
  135. }
  136. }

输出

================》; binlog[mysql-bin.000004:3069] , name[gmall,user_info] , eventType : UPDATE
Table:user_info
EventType:UPDATE
之前数据是:{"sex":"0","name":"a22","id":"4"}
之后数据是:{"sex":"1","name":"a22","id":"4"}

当前抓取没有数据,休息一会。。。。。。

================》; binlog[mysql-bin.000004:3227] , name[gmall,user_info_3] , eventType : CREATE
================》;isDDl: true,sql:CREATE TABLE `user_info_3` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `sex` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci