Canal监听MySQL

Canal监听MySQL

1、Mysql数据库开启binlog模式

注意:Mysql容器,此处Mysql版本为5.7

#进入容器
docker exec -it mysql /bin/bash
#进入配置目录
cd /etc/mysql/mysql.conf.d
#修改配置文件
vi mysqld.cnf

(1) 修改mysqld.cnf配置文件,添加如下配置:
在这里插入图片描述

log-bin=mysql-bin
server-id=12345

(2) 创建账号 用于测试使用,使用root账号创建用户并授予权限

create user canal@'%' IDENTIFIED by 'canal';

GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT,SUPER ON *.* TO 'canal'@'%';

FLUSH PRIVILEGES;

(3) 重启mysql容器

docker restart mysql

2、Docker下Canal容器安装

(1)拉取canal镜像

docker pull docker.io/canal/canal-server

(2)创建Canal容器

docker run -p 11111:11111 --name canal -d docker.io/canal/canal-server

(3)进入容器,修改核心配置canal.properties 和instance.properties,canal.properties 是canal自身的配置,instance.properties是需要同步数据的数据库连接配置。

#进入容器
docker exec -it canal /bin/bash
cd canal-server/conf/
#修改 canal.properties
vi canal.properties
cd example/
#修改 instance.properties
vi instance.properties

修改canal.properties的id,不能和mysql的server-id重复,如下图:
在这里插入图片描述
修改instance.properties,配置数据库连接地址:
在这里插入图片描述
在这里插入图片描述

这里的canal.instance.filter.regex有多种配置,如下:

可以参考地址如下: https://github.com/alibaba/canal/wiki/AdminGuide

mysql 数据解析关注的表,Perl正则表达式.
多个正则之间以逗号(,)分隔,转义符需要双斜杠(\\) 
常见例子:
1.  所有表:.*   or  .*\\..*
2.  canal schema下所有表: canal\\..*
3.  canal下的以canal打头的表:canal\\.canal.*
4.  canal schema下的一张表:canal.test1
5.  多个规则组合使用:canal\\..*,mysql.test1,mysql.test2 (逗号分隔)
注意:此过滤条件只针对row模式的数据有效(ps. mixed/statement因为不解析sql,所以无法准确提取tableName进行过滤)

配置完成后,设置开机启动,并记得重启canal。

docker update --restart=always canal
docker restart canal

3、Canal Client项目搭建

(1)引入依赖

   <parent>
        <artifactId>spring-boot-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <dependencies>
  	<!--canal依赖-->
        <dependency>
            <groupId>com.xpand</groupId>
            <artifactId>starter-canal</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

注意:canal依赖stater在中央仓库是不存在的,需要手动放进本地仓库或者你公司里面的nexus

这里以放进本地仓库为例:

在这里插入图片描述

  • 首先解压spring-boot-starter-canal-master.zip
  • 在spring-boot-starter-canal-master\starter-canal文件夹下执行mvn clean install
  • 此时在本地仓库就会存在jar包
  • 引入依赖
 	<!--canal依赖-->
        <dependency>
            <groupId>com.xpand</groupId>
            <artifactId>starter-canal</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

(2)启动类编写

@SpringBootApplication
@EnableCanalClient
public class CanalApplication {
    public static void main(String[] args) {
        SpringApplication.run(CanalApplication.class,args);
    }
}

(3)监听器编写

@CanalEventListener
public class CanalDataEventListener {

    /***
     * 增加数据监听
     * @param eventType
     * @param rowData
     */
    @InsertListenPoint
    public void onEventInsert(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        rowData.getAfterColumnsList().forEach((c) -> System.out.println("By--Annotation: " + c.getName() + " ::   " + c.getValue()));
    }

    /***
     * 修改数据监听
     * @param rowData
     */
    @UpdateListenPoint
    public void onEventUpdate(CanalEntry.RowData rowData) {
        System.out.println("UpdateListenPoint");
        rowData.getAfterColumnsList().forEach((c) -> System.out.println("By--Annotation: " + c.getName() + " ::   " + c.getValue()));
    }

    /***
     * 删除数据监听
     * @param eventType
     */
    @DeleteListenPoint
    public void onEventDelete(CanalEntry.EventType eventType) {
        System.out.println("DeleteListenPoint");
    }

    /***
     * 自定义数据修改监听
     * @param eventType
     * @param rowData
     */
    @ListenPoint(destination = "example", schema = "torlesse_test", table = {"tb_user", "tb_order"}, eventType = CanalEntry.EventType.UPDATE)
    public void onEventCustomUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        System.err.println("DeleteListenPoint");
        rowData.getAfterColumnsList().forEach((c) -> System.out.println("By--Annotation: " + c.getName() + " ::   " + c.getValue()));
    }


    @ListenPoint(destination = "example",
            schema = "test_canal", //所要监听的数据库名
            table = {"tb_user"}, //所要监听的数据库表名
            eventType = {CanalEntry.EventType.UPDATE, CanalEntry.EventType.INSERT, CanalEntry.EventType.DELETE})
    public void onEventCustomUpdateForTbUser(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        getChangeValue(eventType,rowData);
    }

    public static void getChangeValue(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        if(eventType == CanalEntry.EventType.DELETE){
            rowData.getBeforeColumnsList().forEach(column -> {
                //获取删除前的数据
                System.out.println(column.getName() + " == " + column.getValue());
            });
        }else {
            rowData.getBeforeColumnsList().forEach(column -> {
                //打印改变前的字段名和值
                System.out.println(column.getName() + " == " + column.getValue());
            });

            rowData.getAfterColumnsList().forEach(column -> {
                //打印改变后的字段名和值
                System.out.println(column.getName() + " == " + column.getValue());
            });
        }
    }
}

到此就可以实现Canal监听Mysql

项目gitee地址:test-canal

详情可以查看:

  • https://github.com/alibaba/canal (阿里官方)
  • https://github.com/alibaba/canal/wiki/AdminGuide (阿里官方)
  • https://github.com/chenqian56131/spring-boot-starter-canal (自制starter)
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
为什么要使用canal监听mysql? canal是阿里巴巴开源的用于增量数据同步的工具,可以将mysql的binlog解析成类似于数据库操作的数据,可以实现实时的数据同步、数据备份、数据分析等功能。在日常开发中,我们经常需要将mysql中的数据同步到其他系统或者进行数据分析,使用canal可以方便地实现这些功能。 如何使用springboot监听mysql? 1.引入依赖 在pom.xml文件中添加canal客户端的依赖。 ``` <dependency> <groupId>com.alibaba.otter</groupId> <artifactId>canal.client</artifactId> <version>1.1.4</version> </dependency> ``` 2.配置canal客户端 在application.yml中添加canal客户端的配置信息。 ``` canal: instance: master-address: ${canal.master.address} username: ${canal.username} password: ${canal.password} destination: ${canal.destination} filter: - .*\\..* mq: enabled: false ``` 其中,master-address为canal服务器的地址,username和password为canal服务器的用户名和密码,destination为canal服务器的实例名称。 3.编写监听器 在springboot中使用canal监听mysql需要实现CanalEventListener接口,重写onEvent方法,处理监听到的数据。 ``` @Component public class CanalListener implements CanalEventListener { @Override public void onEvent(CanalEntry.Entry entry) { // 处理监听到的数据 } } ``` 4.启动监听器 在启动类中添加@EnableCanalClient注解,开启canal客户端的监听功能。 ``` @SpringBootApplication @EnableCanalClient public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 通过以上步骤,我们就可以使用springboot监听mysql了。在CanalListener的onEvent方法中,可以处理监听到的数据,实现数据同步、数据备份、数据分析等功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CODING一场空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值