canal可以用来监控数据库数据的变化,从而获得新增数据,或者修改的数据。
canal是应对阿里巴巴存在杭州和美国的双机房部署,存在跨机房同步的业务需求而提出的。
阿里系公司开始逐步的尝试基于数据库的日志解析,获取增量变更进行同步,由此衍生出了增量订阅&消费的业务。
canal将自己伪装成sql的备份机,当数据库发生变化时,会写入Binarylog日志,日志会同步到canal,再由canal同步数据
使用canal的前提是,mysql要开启了binlog模式
1检查是否开启了binlog
这是sql指令
SHOW VARIABLES LIKE '%log_bin%'
如果log_bin的值为OFF是未开启,为ON是已开启。
2 修改/etc/my.cnf以开启binlog模式
[mysqld]
1og-bin=mysql-bin
binlog-format=ROW
server_id=1
3 重启mysql
4 使用root用户登录mysql,在sql中创建一个新用户并授权
create user canal@'%' IDENTIFIED by 'canal';
GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT,SUPER ON *.* TO 'canal'@'%';
FLUSH PRIVILEGES;
安装Canal
1下载地址
https://github.com/alibaba/canal/releases/tag/canal-1.0.24
2在Linux中新建一个目录canal
3将解压包上传到这个目录,解压
4 找到安装目录 vi conf/example/instance.properties 并修改如下参数
canal.instance.master.address=192.168.200.128:3306
canal.instance.dbusername =canal
canal.instance.dbpassword =canal
5 在mysql(linux或者sqlyog都可以)中执行 show master status;

如果File的后缀不为000001,可以执行reset master;
同时要保证 vim /usr/local/canal/conf/example/meta.dat
中的 "journalName":"mysql-bin.000001","position":120,"文件后缀名000001和查出来 的一致,不一定是000001,一样就行
6 启动服务
canal的bin下的 ./startup.sh
7 查看日志
cat /usr/local/canal/logs/canal/canal.log
我们可以用 spring-boot-starter-canal来实现springboot与cannal的集成,比原生的canal更加优雅
下载地址
https://github.com/chenqian56131/spring-boot-starter-canal
选择zip下载,下载好后解压,进入starter-canal文件夹内,打开cmd,输入
mvn clean install -DskipTests
等待解压完成,我不知道为什么没有解压进默认的文件夹,它自己解压到了D盘里我希望的那个文件夹
在仓库的com里有xpand,即为解压成功
在springboot中搭建canal
先构建一个springboot,引入坐标
<dependencies>
<dependency>
<groupId>com.xpand</groupId>
<artifactId>starter-canal</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
</dependency>
</dependencies>
在引导类上加上注解
添加配置文件
canal.client.instances.example.host=192.168.200.128
canal.client.instances.example.port=11111
canal.client.instances.example.batchSize=1000
spring.rabbitmq.host=192.168.200.128
创建一个测试类
@CanalEventListener//声明当前的类是canal的监听类
public class BusinessListener {
@Autowired
private RabbitTemplate rabbitTemplate;
/**
*
* @param eventType 当前操作数据库的类型
* @param rowData 当前操作数据库的数据 changgou_business
*/
@ListenPoint(schema ="changgou_business", table = {"tb_ad"})//声明监听哪个库的哪个表
public void adUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
System.err.println("广告数据发生变化");
//修改前数据
rowData.getBeforeColumnsList().forEach((c)-> System.out.println("改变前的数据:"+c.getName()+"::"+c.getValue()));
//修改后数据
rowData.getAfterColumnsList().forEach((c) -> System.out.println("改变后的数据"+c.getName()+"::"+c.getValue()));
}
}
1
浙公网安备 33010602011771号