一、Canal介绍

1、应用场景

在前面的统计分析功能中,我们采取了服务调用获取统计数据,这样耦合度高,效率相对较低,目前我采取另一种实现方式,通过实时同步数据库表的方式实现,例如我们要统计每天注册与登录人数,我们只需把会员表同步到统计库中,实现本地统计就可以了,这样效率更高,耦合度更低,Canal就是一个很好的数据库同步工具。canal是阿里巴巴旗下的一款开源项目,纯Java开发。基于数据库增量日志解析,提供增量数据订阅&消费,目前主要支持了MySQL。

2、Canal环境搭建

canal的原理是基于mysql binlog技术,所以这里一定需要开启mysql的binlog写入功能
开启mysql服务: service mysql start
(1)检查binlog功能是否有开启

  1. mysql> show variables like 'log_bin';
  2. +---------------+-------+
  3. | Variable_name | Value |
  4. +---------------+-------+
  5. | log_bin | OFF |
  6. +---------------+-------+
  7. 1 row in set (0.00 sec)

(2)如果显示状态为OFF表示该功能未开启,开启binlog功能

  1. 1,修改 mysql 的配置文件 my.cnf
  2. vi /etc/my.cnf
  3. 追加内容:
  4. log-bin=mysql-bin #binlog文件名
  5. binlog_format=ROW #选择row模式
  6. server_id=1 #mysql实例id,不能和canalslaveId重复
  7. 2,重启 mysql
  8. service mysql restart
  9. 3,登录 mysql 客户端,查看 log_bin 变量
  10. mysql> show variables like 'log_bin';
  11. +---------------+-------+
  12. | Variable_name | Value |
  13. +---------------+-------+
  14. | log_bin | ON|
  15. +---------------+-------+
  16. 1 row in set (0.00 sec)
  17. ————————————————
  18. 如果显示状态为ON表示该功能已开启

(3)在mysql里面添加以下的相关用户和权限

  1. CREATE USER 'canal'@'%' IDENTIFIED BY 'canal';
  2. GRANT SHOW VIEW, SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'canal'@'%';
  3. FLUSH PRIVILEGES;

3、下载安装Canal服务

下载地址:https://github.com/alibaba/canal/releases

(1)下载之后,放到目录中,解压文件

cd /usr/local/canal
canal.deployer-1.1.4.tar.gz
tar zxvf canal.deployer-1.1.4.tar.gz

(2)修改配置文件

vi conf/example/instance.properties

  1. #需要改成自己的数据库信息
  2. canal.instance.master.address=192.168.44.132:3306
  3. #需要改成自己的数据库用户名与密码
  4. canal.instance.dbUsername=canal
  5. canal.instance.dbPassword=canal
  6. #需要改成同步的数据库表规则,例如只是同步一下表
  7. #canal.instance.filter.regex=.*\\..*
  8. canal.instance.filter.regex=guli_ucenter.ucenter_member

注:
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进行过滤)


(3)进入bin目录下启动

sh bin/startup.sh

二、创建canal_client模块

1、在guliedu_parent下创建canal_client模块

fa123a9a-2ef5-49f3-a628-6dc428ce9b0b.png

2、引入相关依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <!--mysql-->
  7. <dependency>
  8. <groupId>mysql</groupId>
  9. <artifactId>mysql-connector-java</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>commons-dbutils</groupId>
  13. <artifactId>commons-dbutils</artifactId>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-jdbc</artifactId>
  18. </dependency>
  19. <dependency>
  20. <groupId>com.alibaba.otter</groupId>
  21. <artifactId>canal.client</artifactId>
  22. </dependency>
  23. </dependencies>

3、创建application.properties配置文件

  1. # 服务端口
  2. server.port=10000
  3. # 服务名
  4. spring.application.name=canal-client
  5. # 环境设置:devtestprod
  6. spring.profiles.active=dev
  7. # mysql数据库连接
  8. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  9. spring.datasource.url=jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8
  10. spring.datasource.username=root
  11. spring.datasource.password=root

4、编写canal客户端类

  1. import com.alibaba.otter.canal.client.CanalConnector;
  2. import com.alibaba.otter.canal.client.CanalConnectors;
  3. import com.alibaba.otter.canal.protocol.CanalEntry.*;
  4. import com.alibaba.otter.canal.protocol.Message;
  5. import com.google.protobuf.InvalidProtocolBufferException;
  6. import org.apache.commons.dbutils.DbUtils;
  7. import org.apache.commons.dbutils.QueryRunner;
  8. import org.springframework.stereotype.Component;
  9. import javax.annotation.Resource;
  10. import javax.sql.DataSource;
  11. import java.net.InetSocketAddress;
  12. import java.sql.Connection;
  13. import java.sql.SQLException;
  14. import java.util.Iterator;
  15. import java.util.List;
  16. import java.util.Queue;
  17. import java.util.concurrent.ConcurrentLinkedQueue;
  18. @Component
  19. public class CanalClient {
  20. //sql队列
  21. private Queue<String> SQL_QUEUE = new ConcurrentLinkedQueue<>();
  22. @Resource
  23. private DataSource dataSource;
  24. /**
  25. * canal入库方法
  26. */
  27. public void run() {
  28. CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("192.168.44.132",
  29. 11111), "example", "", "");
  30. int batchSize = 1000;
  31. try {
  32. connector.connect();
  33. connector.subscribe(".*\\..*");
  34. connector.rollback();
  35. try {
  36. while (true) {
  37. //尝试从master那边拉去数据batchSize条记录,有多少取多少
  38. Message message = connector.getWithoutAck(batchSize);
  39. long batchId = message.getId();
  40. int size = message.getEntries().size();
  41. if (batchId == -1 || size == 0) {
  42. Thread.sleep(1000);
  43. } else {
  44. dataHandle(message.getEntries());
  45. }
  46. connector.ack(batchId);
  47. //当队列里面堆积的sql大于一定数值的时候就模拟执行
  48. if (SQL_QUEUE.size() >= 1) {
  49. executeQueueSql();
  50. }
  51. }
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. } catch (InvalidProtocolBufferException e) {
  55. e.printStackTrace();
  56. }
  57. } finally {
  58. connector.disconnect();
  59. }
  60. }
  61. /**
  62. * 模拟执行队列里面的sql语句
  63. */
  64. public void executeQueueSql() {
  65. int size = SQL_QUEUE.size();
  66. for (int i = 0; i < size; i++) {
  67. String sql = SQL_QUEUE.poll();
  68. System.out.println("[sql]----> " + sql);
  69. this.execute(sql.toString());
  70. }
  71. }
  72. /**
  73. * 数据处理
  74. *
  75. * @param entrys
  76. */
  77. private void dataHandle(List<Entry> entrys) throws InvalidProtocolBufferException {
  78. for (Entry entry : entrys) {
  79. if (EntryType.ROWDATA == entry.getEntryType()) {
  80. RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
  81. EventType eventType = rowChange.getEventType();
  82. if (eventType == EventType.DELETE) {
  83. saveDeleteSql(entry);
  84. } else if (eventType == EventType.UPDATE) {
  85. saveUpdateSql(entry);
  86. } else if (eventType == EventType.INSERT) {
  87. saveInsertSql(entry);
  88. }
  89. }
  90. }
  91. }
  92. /**
  93. * 保存更新语句
  94. *
  95. * @param entry
  96. */
  97. private void saveUpdateSql(Entry entry) {
  98. try {
  99. RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
  100. List<RowData> rowDatasList = rowChange.getRowDatasList();
  101. for (RowData rowData : rowDatasList) {
  102. List<Column> newColumnList = rowData.getAfterColumnsList();
  103. StringBuffer sql = new StringBuffer("update " + entry.getHeader().getTableName() + " set ");
  104. for (int i = 0; i < newColumnList.size(); i++) {
  105. sql.append(" " + newColumnList.get(i).getName()
  106. + " = '" + newColumnList.get(i).getValue() + "'");
  107. if (i != newColumnList.size() - 1) {
  108. sql.append(",");
  109. }
  110. }
  111. sql.append(" where ");
  112. List<Column> oldColumnList = rowData.getBeforeColumnsList();
  113. for (Column column : oldColumnList) {
  114. if (column.getIsKey()) {
  115. //暂时只支持单一主键
  116. sql.append(column.getName() + "=" + column.getValue());
  117. break;
  118. }
  119. }
  120. SQL_QUEUE.add(sql.toString());
  121. }
  122. } catch (InvalidProtocolBufferException e) {
  123. e.printStackTrace();
  124. }
  125. }
  126. /**
  127. * 保存删除语句
  128. *
  129. * @param entry
  130. */
  131. private void saveDeleteSql(Entry entry) {
  132. try {
  133. RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
  134. List<RowData> rowDatasList = rowChange.getRowDatasList();
  135. for (RowData rowData : rowDatasList) {
  136. List<Column> columnList = rowData.getBeforeColumnsList();
  137. StringBuffer sql = new StringBuffer("delete from " + entry.getHeader().getTableName() + " where ");
  138. for (Column column : columnList) {
  139. if (column.getIsKey()) {
  140. //暂时只支持单一主键
  141. sql.append(column.getName() + "=" + column.getValue());
  142. break;
  143. }
  144. }
  145. SQL_QUEUE.add(sql.toString());
  146. }
  147. } catch (InvalidProtocolBufferException e) {
  148. e.printStackTrace();
  149. }
  150. }
  151. /**
  152. * 保存插入语句
  153. *
  154. * @param entry
  155. */
  156. private void saveInsertSql(Entry entry) {
  157. try {
  158. RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
  159. List<RowData> rowDatasList = rowChange.getRowDatasList();
  160. for (RowData rowData : rowDatasList) {
  161. List<Column> columnList = rowData.getAfterColumnsList();
  162. StringBuffer sql = new StringBuffer("insert into " + entry.getHeader().getTableName() + " (");
  163. for (int i = 0; i < columnList.size(); i++) {
  164. sql.append(columnList.get(i).getName());
  165. if (i != columnList.size() - 1) {
  166. sql.append(",");
  167. }
  168. }
  169. sql.append(") VALUES (");
  170. for (int i = 0; i < columnList.size(); i++) {
  171. sql.append("'" + columnList.get(i).getValue() + "'");
  172. if (i != columnList.size() - 1) {
  173. sql.append(",");
  174. }
  175. }
  176. sql.append(")");
  177. SQL_QUEUE.add(sql.toString());
  178. }
  179. } catch (InvalidProtocolBufferException e) {
  180. e.printStackTrace();
  181. }
  182. }
  183. /**
  184. * 入库
  185. * @param sql
  186. */
  187. public void execute(String sql) {
  188. Connection con = null;
  189. try {
  190. if(null == sql) return;
  191. con = dataSource.getConnection();
  192. QueryRunner qr = new QueryRunner();
  193. int row = qr.execute(con, sql);
  194. System.out.println("update: "+ row);
  195. } catch (SQLException e) {
  196. e.printStackTrace();
  197. } finally {
  198. DbUtils.closeQuietly(con);
  199. }
  200. }
  201. }

5、创建启动类

  1. @SpringBootApplication
  2. public class CanalApplication implements CommandLineRunner {
  3. @Resource
  4. private CanalClient canalClient;
  5. public static void main(String[] args) {
  6. SpringApplication.run(CanalApplication.class, args);
  7. }
  8. @Override
  9. public void run(String... strings) throws Exception {
  10. //项目启动,执行canal客户端监听
  11. canalClient.run();
  12. }
  13. }