前文:
採集Mysql的binlog同步到Kafka,下游可採用Spark解析對應的Binlog日誌發送到不同的數據庫。
一、配置
1、Maxwell配置
vim /opt/maxwell-1.24.0/config.properties
#日誌
log_level=info
#Kafka配置
producer=kafka
kafka.bootstrap.servers=hadoop101:9092,hadoop102:9092,hadoop103:9092
kafka.compression.type=snappy
kafka.retries=0
kafka.acks=1
producer_partition_by=primary_key
#發送到Kafka對應的主題,可指定也可按如下匹配
kafka_topic=maxwell_%{table}
#Mysql數據庫配置
host=hadoop101
port=3306
user=root
password=123456
#client_id爲記錄在Maxwell的客戶端id,用於協調檢測
#replica_server_id爲從Mysql拉取binlog日誌的id標誌
client_id=1921681101
replica_server_id=1921681101
#匹配Mysql的數據庫及對應的表
filter = exclude: *.*,include: test.student
2、Mysql開啓Binlog
mysql> GRANT ALL on *.* to 'maxwell'@'192.168.1.101' identified by '123456' ;
mysql> GRANT SELECT, REPLICATION CLIENT, REPLICATION SLAVE on *.* to 'maxwell'@'192.168.1.101';
mysql> flush privaleges;
mysql> flush logs;
#重啓Mysql
systemctl restart mysqld.service
3、啓動Maxwell
cd /opt/maxwell-1.24.0
nohup ./bin/maxwell &
4、自動監控腳本
source /etc/profile
#監聽對應maxwell的路徑
maxwell_path="/opt/maxwell-1.24.0"
rusult=`pgrep -af $(basename $BASH_SOURCE) | wc -l` #監聽此腳本是否啓動,編輯此腳本時也被識別爲啓動
#crontab的運行環境與我們手動執行的環境不同
#未啓動:啓動腳本+判斷腳本=2
#運行中:啓動腳本+判斷腳本+已存在進程=3 ,編輯此腳本則 3+1 =4
if [ "$rusult" = "2" ];then
cd $maxwell_path && nohup ./bin/maxwell &
curl http://127.0.0.1:10085/sender/mail -d "[email protected]&subject=Maxwell 出現故障!!&content=$(basename $BASH_SOURCE) 出現異常,觸發重啓機制。"
echo " `date "+%Y-%m-%d %H:%M:%S"` $maxwell_path 啓動成功!" >> /home/caijiasheng/listen_maxwell_log
else
echo `date "+%Y-%m-%d %H:%M:%S"` $(basename $BASH_SOURCE) rusult=$rusult "運行中" >> /home/caijiasheng/listen_maxwell_log
fi
5、定時啓動
crontab -e
*/30 * * * * sh /home/cesar/listen_maxwell-1.24.0.sh > /dev/null 2>&1 &
6、代碼解析(以下爲Scala方式)
樣例類
case class GetMaxWelllog(
@SerializedName("type")
`type`: String,
@SerializedName("database")
database: String,
@SerializedName("table")
table: String,
@SerializedName("old")
old: JsonObject,
@SerializedName("data")
data: JsonObject
)
工具類
package com.google.gson;
public final class Gson {
//核心對象
public Gson() {}
//核心方法
public <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException {}
解析過程
val gson = new Gson
val jsonObj = gson.fromJson[GetMaxWelllog](Maxwelljson.toString, classOf[GetMaxWelllog])