springboot使用canal监听数据库变动
前置条件:mysql需要开启主从同步
一、docker安装canal
# 拉取镜像
docker pull canal/canal-server:latest
# 运行容器 docker run -p 11111:11111 --name=canal-server \ --net=my_network \ -e canal.auto.scan=false \ -e canal.destinations=test \ -e canal.instance.master.address=master_mysql:3306 \ -e canal.instance.dbUsername=slave \ -e canal.instance.dbPassword=123456 \ -e canal.instance.connectionCharset=UTF-8 \ -e canal.instance.tsdb.enable=true \ -e canal.instance.gtidon=false \ -e canal.instance.filter.regex=.*\\..* \ -d canal/canal-server
二、springboot引入maven依赖
<dependency> <groupId>top.javatool</groupId> <artifactId>canal-spring-boot-starter</artifactId> <version>1.2.1-RELEASE</version> </dependency>
三、与springboot整合
1、配置yml
canal:
destination: test # 与canal启动的名称保持一样
server: 192.168.33.88:11111
2、准备实体类
import javax.persistence.Column; import javax.persistence.Id; import lombok.Data; import com.base.common.core.domain.BaseEntity; /** * 用户对象 sys_user * * @author base */ @Data public class SysUser extends BaseEntity { private static final long serialVersionUID = 1L; @Id @Column(name = "user_id") private Long userId; @Column(name = "dept_id") private Long deptId; @Column(name = "user_name") private String userName; @Column(name = "nick_name") private String nickName; @Column(name = "email") private String email; @Column(name = "phonenumber") private String phonenumber; }
3、编写监听类
import com.base.common.core.domain.entity.SysUser; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import top.javatool.canal.client.annotation.CanalTable; import top.javatool.canal.client.handler.EntryHandler; @CanalTable("sys_user") @Component @Slf4j public class SysUserHandler implements EntryHandler<SysUser> { @Override public void insert(SysUser sysUser) { log.info("用户信息新增:-------------{}", sysUser); } @Override public void update(SysUser before, SysUser after) { log.info("用户信息变更前:-------------{}", before); log.info("用户信息变更后:-------------{}", after); } @Override public void delete(SysUser sysUser) { log.info("用户信息删除:-------------{}", sysUser); } }
四、配置top.javatool.canal.client包下面的日志打印级别为warn(否则会有很多日志输出)
logging:
level:
top.javatool.canal.client: warn
五、启动项目测试,操作sys_user表即可触发SysUserHandler中的对应方法
注意:数据库字段中使用的下划线,实体类中使用的是驼峰命名时,必须使用@Column映射字段,否则监听到的字段值为空