1.canal的用途
主要用途是基于 MySQL 数据库增量日志解析,提供增量数据订阅和消费
2.canal的工作原理
(1)canal 模拟 MySQL slave 的交互协议,伪装自己为 MySQL slave ,向 MySQL master 发送 dump 协议
(2)MySQL master 收到 dump 请求,开始推送 binary log 给 slave (即 canal )
(3)canal 解析 binary log 对象(原始为 byte 流)
3.canal安装前的准备工作
(1)mysql开启Binlog写入功能。
通过数据库可视化工具或者mysql命令行执行命令:SHOW VARIABLES LIKE ‘log_bin’; 如果查询结果为ON表示开启,OFF表示关闭
如果该功能关闭,需要修改mysql配置文件并重启mysql服务
配置文件新增配置:
log-bin=mysql-bin # 开启 binlog
binlog-format=ROW # 选择 ROW 模式
server_id=1 # 配置 MySQL replaction 需要定义,不要和 canal 的 slaveId 重复
(2)授权 canal 链接 MySQL 账号具有作为 MySQL slave 的权限
CREATE USER ‘canal’@‘%’ IDENTIFIED BY ‘password’;
GRANT ALL PRIVILEGES ON . TO ‘canal’@‘%’ IDENTIFIED BY ‘password’;
FLUSH PRIVILEGES;
4.canal的下载与安装
(1)访问官网地址:https://github.com/alibaba/canal,点击右侧的【Releares】,鼠标下滑,我们以1.1.6版本的canal为例,下载对应版本的tar包
(2)将tar包上传至linux服务器,执行命令 tar -zxvf 解压tar包,解压后的结构如下所示
(3)修改配置文件
进入/conf/example文件夹,使用命令vim instance.properties命令编辑配置文件
(4)启动canal
进入/bin文件夹,执行命令 ./startup.sh 命令启动canal服务
(5)验证
进入/logs/canal文件夹,执行命令vim canal.log查看日志
进入/logs/example文件夹,执行命令vim example.log查看日志
出现上图所示的日志打印证明canal服务启动成功
5.springboot集成canal
先配置maven依赖
> <dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>canal.client</artifactId>
<version>1.1.0</version>
</dependency>
package com.alibaba.otter.canal.sample;
import java.net.InetSocketAddress;
import java.util.List;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.common.utils.AddressUtils;
import com.alibaba.otter.canal.protocol.Message;
import com.alibaba.otter.canal.protocol.CanalEntry.Column;
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.EntryType;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;
public class SimpleCanalClientExample {
public static void main(String args[]) {
// 创建链接
CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("127.0.0.1",
11111), "example", "", "");
int batchSize = 1000;
int emptyCount = 0;
try {
connector.connect();
connector.subscribe(".*\\..*"); //监听所有数据库的所有表的数据变动
connector.rollback();
int totalEmptyCount = 120;
while (emptyCount < totalEmptyCount) {
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) {
}
} 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());
} 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());
}
}
}
6.程序验证
通过mysql可视化工具或者mysql命令行向表中新增数据,程序成功监听