### canal 工做思路html
Canal 會將本身假裝成 MySQL 從節點(Slave),並從主節點(Master)獲取 Binlog,解析和貯存後供下游消費端使用。Canal 包含兩個組成部分:服務端和客戶端。服務端負責鏈接至不一樣的 MySQL 實例,併爲每一個實例維護一個事件消息隊列;客戶端則能夠訂閱這些隊列中的數據變動事件,處理並存儲到數據倉庫中。下面咱們將mysql同步到 redisjava
mysql版本 5.6mysql
canal版本 1.1.0git
安裝 mysql 後修改本身mysql配置github
vim /etc/my.cnf
web
# 開啓mysql的binlog模塊 log-bin=mysql-bin binlog-format=ROW # server_id需保證惟一,不能和canal的slaveId重複 server_id=121 # 須要同步的數據庫名稱 binlog-do-db=test_canal # 忽略的數據庫,建議填寫 binlog-ignore-db=mysql # 啓動mysql時不啓動grant-tables受權表 skip-grant-tables
建立一個mysql用戶canal
而且賦遠程連接權限權限,和測試庫test_canal
,redis
CREATE USER canal IDENTIFIED BY 'canal'; GRANT ALL PRIVILEGES ON test_canal.user TO 'canal'@'%'; FLUSH PRIVILEGES;
使用root帳戶進去看看
select * from mysql.user where user=’canal’ \G
其查詢結果列表中Repl_slave_priv
,Repl_client_priv
中的爲Y是對的,查看主從備份以下圖:sql
下載canal:https://github.com/alibaba/canal/releases/shell
下載版本爲1.1.0,解壓便可數據庫
tar -zxvf canal.deployer-1.1.0.tar.gz -C /usr/local/cancal/
解壓後獲得四個目錄bin、conf、lib、logs
基本上配置都在一下兩個配置文件中
canal.properties無需修改 ,instance.properties須要配置所同步的組件
instance.properties
配置以下
################################################# ## mysql serverId , v1.0.26+ will autoGen #與mysql配置文件一致 canal.instance.mysql.slaveId=121 # enable gtid use true/false canal.instance.gtidon=false # position info canal.instance.master.address=ip:3306 canal.instance.master.journal.name= canal.instance.master.position= canal.instance.master.timestamp= canal.instance.master.gtid= # rds oss binlog canal.instance.rds.accesskey= canal.instance.rds.secretkey= canal.instance.rds.instanceId= # table meta tsdb info #暫時用不上設爲false canal.instance.tsdb.enable=false canal.instance.tsdb.dir=${canal.file.data.dir:../conf}/${canal.instance.destination:} canal.instance.tsdb.url=jdbc:h2:${canal.instance.tsdb.dir}/h2;CACHE_SIZE=1000;MODE=MYSQL; #canal.instance.tsdb.url=jdbc:mysql://127.0.0.1:3306/canal_tsdb canal.instance.tsdb.dbUsername=canal canal.instance.tsdb.dbPassword=canal #canal.instance.standby.address = #canal.instance.standby.journal.name = #canal.instance.standby.position = #canal.instance.standby.timestamp = #canal.instance.standby.gtid= # username/password canal.instance.dbUsername=canal canal.instance.dbPassword=canal canal.instance.defaultDatabaseName=test_canal canal.instance.connectionCharset=UTF-8 # table regex canal.instance.filter.regex=.*\\..* # table black regex canal.instance.filter.black.regex= #################################################
查看日誌是否啓動成功:logs/canal/canal.log 和logs/example/example.log
logs/canal/canal.log文件中有以下內容:the canal server is running now ......
logs/example/example.log文件中有以下內容:start successful....
在項目maven中添加redis和canal依賴
<dependency> <groupId>com.alibaba.otter</groupId> <artifactId>canal.client</artifactId> <version>1.0.25</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
redis工具類:
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * @author lgz */ public class RedisUtil { private static Jedis jedis = null; public static synchronized Jedis getJedis() { if (jedis == null) { jedis = new Jedis("192.168.188.128", 6379); jedis.auth("redis1234"); } return jedis; } public static boolean existKey(String key) { return getJedis().exists(key); } public static void delKey(String key) { getJedis().del(key); } public static String stringGet(String key) { return getJedis().get(key); } public static String stringSet(String key, String value) { return getJedis().set(key, value); } public static void hashSet(String key, String field, String value) { getJedis().hset(key, field, value); } }
canal客戶端:
package com.wlx.demo.config; import com.alibaba.fastjson.JSONObject; import com.alibaba.otter.canal.client.CanalConnector; import com.alibaba.otter.canal.client.CanalConnectors; import com.alibaba.otter.canal.protocol.CanalEntry.*; import com.alibaba.otter.canal.protocol.Message; import java.net.InetSocketAddress; import java.util.List; /** * Created by zhangpan on 2019/1/4. */ public class CanalApplication { public static void main(String args[]) { CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("ip", 11111), "example", "", ""); int batchSize = 100; try { connector.connect(); connector.subscribe(".*\\..*"); connector.rollback(); while (true) { // 獲取指定數量的數據 Message message = connector.getWithoutAck(batchSize); long batchId = message.getId(); int size = message.getEntries().size(); System.out.println("batchId = " + batchId); System.out.println("size = " + size); if (batchId == -1 || size == 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } else { printEntry(message.getEntries()); } // 提交確認 connector.ack(batchId); // connector.rollback(batchId); // 處理失敗, 回滾數據 } } 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) { redisDelete(rowData.getBeforeColumnsList()); } else if (eventType == EventType.INSERT) { redisInsert(rowData.getAfterColumnsList()); } else { System.out.println("-------> before"); printColumn(rowData.getBeforeColumnsList()); System.out.println("-------> after"); redisUpdate(rowData.getAfterColumnsList()); } } } } private static void printColumn(List<Column> columns) { for (Column column : columns) { System.out.println(column.getName() + " : " + column.getValue() + " update=" + column.getUpdated()); } } private static void redisInsert(List<Column> columns) { JSONObject json = new JSONObject(); for (Column column : columns) { json.put(column.getName(), column.getValue()); } if (columns.size() > 0) { RedisUtil.stringSet("user:" + columns.get(0).getValue(), json.toJSONString()); } } private static void redisUpdate(List<Column> columns) { JSONObject json = new JSONObject(); for (Column column : columns) { json.put(column.getName(), column.getValue()); } if (columns.size() > 0) { RedisUtil.stringSet("user:" + columns.get(0).getValue(), json.toJSONString()); } } private static void redisDelete(List<Column> columns) { JSONObject json = new JSONObject(); for (Column column : columns) { json.put(column.getName(), column.getValue()); } if (columns.size() > 0) { RedisUtil.delKey("user:" + columns.get(0).getValue()); } } }
在test_canal
新建user
表,
CREATE TABLE `user` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
添加數據能夠在控制檯看到消息:
INSERT INTO
user(id,name) VALUES (1,'zhangpan');
控制檯消息
size = 3 ================> binlog[mysql-bin.000005:5001] , name[test_canal,user] , eventType : INSERT
參考博客:https://blog.csdn.net/lyl0724/article/details/80528428
轉載請說明出處!謝謝,本文地址:http://www.javashuo.com/article/p-yxgwncxg-ek.html