使用canal監(jiān)控mysql數(shù)據(jù)庫實(shí)現(xiàn)elasticsearch索引實(shí)時(shí)更新問題
業(yè)務(wù)場(chǎng)景
- 使用elasticsearch作為全文搜索引擎,對(duì)標(biāo)題、內(nèi)容等,實(shí)現(xiàn)智能搜索、輸入提示、拼音搜索等
- elasticsearch索引與數(shù)據(jù)庫數(shù)據(jù)不一致,導(dǎo)致搜索到不應(yīng)被搜到的結(jié)果,或者搜不到已有數(shù)據(jù)
- 索引相關(guān)業(yè)務(wù),影響其他業(yè)務(wù)操作,如索引刪除失敗導(dǎo)致數(shù)據(jù)庫刪除失敗
- 為了減少對(duì)現(xiàn)有業(yè)務(wù)的侵入,基于數(shù)據(jù)庫層面,對(duì)信息表進(jìn)行監(jiān)控,但需要索引的字段變動(dòng)時(shí),更新索引
- 由于使用的是mysql數(shù)據(jù)庫,故決定采用alibaba的canal中間件
- 主要是監(jiān)控信息基表base,監(jiān)控這一張表的數(shù)據(jù)變動(dòng),mq消息消費(fèi)時(shí),重新從數(shù)據(jù)庫查詢數(shù)據(jù)更新或刪除索引(數(shù)據(jù)無法直接使用,要數(shù)據(jù)清洗,需要關(guān)聯(lián)查詢拼接處理等)
- 大致邏輯
數(shù)據(jù)庫變動(dòng) -> 產(chǎn)生binlog -> canal監(jiān)控讀取binlog -> 發(fā)送mq -> 索引服務(wù)消費(fèi)mq -> 查詢數(shù)據(jù)庫 -> 更新索引 -> 消息ack
安裝
下載安裝
wget 地址解壓即可修改配置即可啟動(dòng)使用wget 下載太慢了,可以自己下載下來再傳到centos服務(wù)器里github1.1.5地址:https://github.com/alibaba/canal/releases/tag/canal-1.1.5
數(shù)據(jù)庫啟用row binlog
- 修改mysql數(shù)據(jù)庫 my.cnf
- 開啟 Binlog 寫入功能,配置 binlog-format 為 ROW 模式
log-bin=mysql-bin # 開啟 binlog binlog-format=ROW # 選擇 ROW 模式 server_id=1 # 配置 replaction 不要和 canal 的 slaveId 重復(fù)
建立canal授權(quán)賬號(hào)
CREATE USER canal IDENTIFIED BY 'canal'; GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'canal'@'%'; FLUSH PRIVILEGES;
使用
修改配置文件canal.properties
- 主配置文件
canal.properties - 配置你的連接
canal.destinations = example,默認(rèn)了個(gè)example - 啟用rabbitMQ
canal.serverMode = rabbitMQ
################################################## ######### RabbitMQ ############# # 提前建好 用戶、vhost、exchange ################################################## rabbitmq.host = 192.168.1.171:5672 rabbitmq.virtual.host = sql rabbitmq.exchange = sqlBinLogExchange rabbitmq.username = admin rabbitmq.password = admin rabbitmq.deliveryMode = Direct
配置單個(gè)連接
canal/conf/下- 修改
instance.properties - 需要配置數(shù)據(jù)庫連接
canal.instance.master.address - 配置表過濾規(guī)則,
canal.instance.filter.regex,注意.和\\ - 配置路由規(guī)則
canal.mq.topic
示例如下
################################################# ## mysql serverId , v1.0.26+ will autoGen # canal.instance.mysql.slaveId=0 # enable gtid use true/false canal.instance.gtidon=false # position info 寫連接即可,其他省略,會(huì)自動(dòng)獲取 canal.instance.master.address=192.168.1.175: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 canal.instance.tsdb.enable=true #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 先前建好的數(shù)據(jù)庫用戶名密碼 canal.instance.dbUsername=canal canal.instance.dbPassword=canal canal.instance.connectionCharset = UTF-8 # enable druid Decrypt database password canal.instance.enableDruid=false #canal.instance.pwdPublicKey=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALK4BUxdDltRRE5/zXpVEVPUgunvscYFtEip3pmLlhrWpacX7y7GCMo2/JM6LeHmiiNdH1FWgGCpUfircSwlWKUCAwEAAQ== # table regex 只監(jiān)控部分表 canal.instance.filter.regex=.*\\.cms_base_content # table black regex canal.instance.filter.black.regex=mysql\\.slave_.* # table field filter(format: schema1.tableName1:field1/field2,schema2.tableName2:field1/field2) #canal.instance.filter.field=test1.t_product:id/subject/keywords,test2.t_company:id/name/contact/ch # table field black filter(format: schema1.tableName1:field1/field2,schema2.tableName2:field1/field2) #canal.instance.filter.black.field=test1.t_product:subject/product_image,test2.t_company:id/name/contact/ch # mq config 這個(gè)是routerkey,要配置 canal.mq.topic=anhui_szf # dynamic topic route by schema or table regex #canal.mq.dynamicTopic=mytest1.user,mytest2\\..*,.*\\..* canal.mq.partition=0 # hash partition config #canal.mq.partitionsNum=3 #canal.mq.partitionHash=test.table:id^name,.*\\..* #canal.mq.dynamicTopicPartitionNum=test.*:4,mycanal:6
配置多個(gè)連接
- 在
conf下新建文件夾,復(fù)制一份instance.properties - 在
canal.destinations里添加上面的文件夾名稱 - 可以使用不同的
canal.mq.topic,路由到不同隊(duì)列
配置rabbitMQ
- 登入你的rabbitMQ管理界面
http://192.168.1.***:15672/ - 確保用戶存在,且有權(quán)限
- 確保vhost存在,沒使用默認(rèn)的
/,則創(chuàng)建

新建你的exchange

新建你的queue

根據(jù)前面配置的topic,作為routerkey將exchange與queue起來

程序改動(dòng)
canal源碼
- 修改
CanalRabbitMQProducer.java - 實(shí)現(xiàn)只監(jiān)控部分字段
- 處理mq消息體,去除不需要的東西,減少數(shù)據(jù)傳輸
- 主要修改了
send(MQDestination canalDestination, String topicName, Message messageSub)
package com.alibaba.otter.canal.connector.rabbitmq.producer;
... ... 省略
@SPI("rabbitmq")
public class CanalRabbitMQProducer extends AbstractMQProducer implements CanalMQProducer {
// 需要監(jiān)控的操作類型
private static final String OPERATE_TYPE = "UPDATE,INSERT,DELETE";
// 更新時(shí),需要觸發(fā)發(fā)送mq的字段
private static final String[] KEY_FIELDS = new String[]{"COLUMN_ID","TITLE","REDIRECT_LINK","IMAGE_LINK",
"IS_PUBLISH","PUBLISH_DATE","RECORD_STATUS","IS_TOP","AUTHOR","REMARKS","TO_FILEID","UPDATE_USER_ID"};
// 數(shù)據(jù)處理時(shí),需要保留的字段(需把標(biāo)題等傳值過去,已刪除數(shù)據(jù)這些查不到了)
private static final String[] HOLD_FIELDS = new String[]{"ID", "SITE_ID", "COLUMN_ID", "RECORD_STATUS", "TITLE"};
... ... 省略
private void send(MQDestination canalDestination, String topicName, Message messageSub) {
if (!mqProperties.isFlatMessage()) {
byte[] message = CanalMessageSerializerUtil.serializer(messageSub, mqProperties.isFilterTransactionEntry());
if (logger.isDebugEnabled()) {
logger.debug("send message:{} to destination:{}", message, canalDestination.getCanalDestination());
}
sendMessage(topicName, message);
} else {
// 并發(fā)構(gòu)造
MQMessageUtils.EntryRowData[] datas = MQMessageUtils.buildMessageData(messageSub, buildExecutor);
// 串行分區(qū)
List<FlatMessage> flatMessages = MQMessageUtils.messageConverter(datas, messageSub.getId());
for (FlatMessage flatMessage : flatMessages) {
if (!OPERATE_TYPE.contains(flatMessage.getType())) {
continue;
}
// 只有設(shè)置的關(guān)鍵字段更新,才會(huì)觸發(fā)消息發(fā)送
if ("UPDATE".equals(flatMessage.getType())) {
List<Map<String, String>> olds = flatMessage.getOld();
if (olds.size() > 0) {
Map<String, String> param = olds.get(0);
// 判斷更新字段是否包含重要字段,不包含則跳過
boolean isSkip = true;
for (String keyField : KEY_FIELDS) {
if (param.containsKey(keyField) || param.containsKey(keyField.toLowerCase())) {
isSkip = false;
break;
}
}
if (isSkip) {
continue;
}
// 取出data里面的ID和RECORD_STATUS,只保留這個(gè)字段的值,其余的舍棄
if (null != flatMessage.getData()) {
List<Map<String, String>> data = flatMessage.getData();
if (!data.isEmpty()) {
List<Map<String, String>> newData = new ArrayList<>();
for(Map<String, String> map : data) {
Map<String, String> newMap = new HashMap<>(8);
for (String field : HOLD_FIELDS) {
if (map.containsKey(field) || map.containsKey(field.toLowerCase())) {
newMap.put(field, map.get(field));
}
newData.add(newMap);
flatMessage.setData(newData);
// 不需要的字段注釋掉,較少網(wǎng)絡(luò)傳輸消耗
flatMessage.setMysqlType(null);
flatMessage.setSqlType(null);
flatMessage.setOld(null);
flatMessage.setIsDdl(null);
logger.info("====================================");
logger.info(JSON.toJSONString(flatMessage));
byte[] message = JSON.toJSONBytes(flatMessage, SerializerFeature.WriteMapNullValue);
if (logger.isDebugEnabled()) {
logger.debug("send message:{} to destination:{}", message, canalDestination.getCanalDestination());
sendMessage(topicName, message);
}
}
... ... 省略
}
微服務(wù)消費(fèi)mq
- 根據(jù)前面的mq配置,建立rabbitMQ連接
- 根據(jù)前面設(shè)置好的
exchange與queue,消費(fèi)mq即可 - 更新或刪除索引
- ack確認(rèn)索引更新失敗的,根據(jù)情況,nack或者存入失敗表
- 由于使用的Springboot版本較低,無法使用批量消費(fèi)接口,只好使用拉模式,主動(dòng)消費(fèi)了
- 部分代碼
package cn.lonsun.core.middleware.rabbitmq;
import cn.lonsun.core.util.SpringContextHolder;
import cn.lonsun.es.internal.service.IIndexService;
import cn.lonsun.es.internal.service.impl.IndexServiceImpl;
import cn.lonsun.es.vo.MessageVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author yanyulin
* @ClassName: MessageListenerBean
* @Description: RabbitMQ消息接收者
* @date 2022-3-14 15:25
* @version: 1.0
*/
@Component
public class MessageListenerBean implements ChannelAwareMessageListener {
private static Logger log = LoggerFactory.getLogger(MessageListenerBean.class);
@Autowired
private RedisTemplate redisTemplate;
// 一次處理多少條消息,考慮es寫入性能(文本較大時(shí),單個(gè)索引可能很大),一次處理200條,模擬剩余多少條,使用2
private static final int BATCH_DEAL_COUNT = 2;
// mq里待消費(fèi)線程緩存KEY
public static final String WAIT_DEAL = "wait_deal";
// 集合編碼
private String code;
@Override
public void onMessage(Message message, Channel channel) throws IOException {
Thread thread=Thread.currentThread();
long maxDeliveryTag = 0;
String queuName = message.getMessageProperties().getConsumerQueue();
// 消費(fèi)前,更新剩余待消費(fèi)消息數(shù)量
redisTemplate.opsForValue().set(code + "_" + WAIT_DEAL, channel.messageCount(queuName) + 1);
System.out.println("==============>" + code + "=" + redisTemplate.opsForValue().get(code + "_" + WAIT_DEAL));
List<MessageVO> messageVOList = new ArrayList<>();
List<GetResponse> responseList = new ArrayList<>();
while (responseList.size() < BATCH_DEAL_COUNT) {
// 需要設(shè)置false,手動(dòng)ack
GetResponse getResponse = channel.basicGet(queuName, false);
if (getResponse == null) {
byte[] body = message.getBody();
String str = new String(body);
log.info(code + " deliveryTag:{} message:{} ThreadId is:{} ConsumerTag:{} Queue:{} channel:{}"
,maxDeliveryTag,str,thread.getId(),message.getMessageProperties().getConsumerTag()
,message.getMessageProperties().getConsumerQueue(),channel.getChannelNumber());
// 開始消費(fèi)
MessageVO messageVO = JSONObject.parseObject(str,MessageVO.class);
log.debug("監(jiān)聽數(shù)據(jù)庫cms_base_content表變更記錄消息,消息內(nèi)容: {} ", JSON.toJSONString(messageVO));
messageVOList.add(messageVO);
break;
}
responseList.add(getResponse);
maxDeliveryTag = getResponse.getEnvelope().getDeliveryTag();
}
try{
if (!responseList.isEmpty()) {
for (GetResponse response : responseList) {
byte[] body = response.getBody();
String str = new String(body);
log.info(code + " deliveryTag:{} message:{} ThreadId is:{} ConsumerTag:{} Queue:{} channel:{}"
,maxDeliveryTag,str,thread.getId(),message.getMessageProperties().getConsumerTag()
,message.getMessageProperties().getConsumerQueue(),channel.getChannelNumber());
// 開始消費(fèi)
MessageVO messageVO = JSONObject.parseObject(str,MessageVO.class);
log.debug("監(jiān)聽數(shù)據(jù)庫cms_base_content表變更記錄消息,消息內(nèi)容: {} ", JSON.toJSONString(messageVO));
messageVOList.add(messageVO);
}
IIndexService indexService = SpringContextHolder.getBean(IndexServiceImpl.class);
indexService.batchDealIndex(messageVOList, code);
channel.basicAck(maxDeliveryTag, true);
// Ack后,更新剩余待消費(fèi)消息數(shù)量
redisTemplate.opsForValue().set(code + "_" + WAIT_DEAL, channel.messageCount(queuName));
System.out.println("==============>" + code + "=" + redisTemplate.opsForValue().get(code + "_" + WAIT_DEAL));
}catch(Throwable e){
log.error("監(jiān)聽前臺(tái)訪問記錄消息,deliveryTag: {} ",maxDeliveryTag,e);
//成功收到消息
try {
channel.basicNack(maxDeliveryTag,true,true);
} catch (IOException e1) {
log.error("ack 異常, 消息隊(duì)列可能出現(xiàn)無法消費(fèi)情況, 請(qǐng)及時(shí)處理",e1);
}
public MessageListenerBean() {
public MessageListenerBean(String code) {
this.code = code;
}
到此這篇關(guān)于使用canal監(jiān)控mysql數(shù)據(jù)庫實(shí)現(xiàn)elasticsearch索引實(shí)時(shí)更新的文章就介紹到這了,更多相關(guān)canal監(jiān)控mysql數(shù)據(jù)庫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- MySQL數(shù)據(jù)同步Elasticsearch的4種方案
- logstash將mysql數(shù)據(jù)同步到elasticsearch方法詳解
- 使用logstash同步mysql數(shù)據(jù)到elasticsearch實(shí)現(xiàn)
- Mysql到Elasticsearch高效實(shí)時(shí)同步Debezium實(shí)現(xiàn)
- 詳解Mysql如何實(shí)現(xiàn)數(shù)據(jù)同步到Elasticsearch
- 用python簡(jiǎn)單實(shí)現(xiàn)mysql數(shù)據(jù)同步到ElasticSearch的教程
- MySQL 與 Elasticsearch 數(shù)據(jù)不對(duì)稱問題解決辦法
- 如何在Elasticsearch中啟用和使用SQL功能
相關(guān)文章
MySQL數(shù)據(jù)庫簡(jiǎn)介與基本操作
這篇文章介紹了MySQL數(shù)據(jù)庫與其基本操作,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05
SQLServer 2005 自動(dòng)備份數(shù)據(jù)庫的方法分享(附圖解教程)
SQLServer 2005 自動(dòng)備份數(shù)據(jù)庫的方法分享(附圖解教程),使用sqlserver2005的朋友可以參考下。2011-09-09
mysql?binlog查看指定數(shù)據(jù)庫的操作方法
MySQL 的 binlog(二進(jìn)制日志)主要記錄了數(shù)據(jù)庫上執(zhí)行的所有更改數(shù)據(jù)的 SQL 語句,包括數(shù)據(jù)的插入、更新和刪除等操作這篇文章主要介紹了mysql?binlog查看指定數(shù)據(jù)庫的方法,需要的朋友可以參考下2024-06-06
mysql:Can''t start server: can''t create PID file: No space
這篇文章主要介紹了mysql啟動(dòng)失敗不能正常啟動(dòng)并報(bào)錯(cuò)Can't start server: can't create PID file: No space left on device問題解決方法,需要的朋友可以參考下2015-05-05
Mysql5.7中使用group concat函數(shù)數(shù)據(jù)被截?cái)嗟膯栴}完美解決方法
前幾天在項(xiàng)目中遇到一個(gè)問題,使用 GROUP_CONCAT 函數(shù)select出來的數(shù)據(jù)被截?cái)嗔?,最長(zhǎng)長(zhǎng)度不超過1024字節(jié),開始還以為是navicat客戶端自身對(duì)字段長(zhǎng)度做了限制的問題。后來查找出原因,解決方法大家跟隨腳本之家小編一起看看吧2018-03-03
Mysql查詢數(shù)據(jù)庫或數(shù)據(jù)表中的數(shù)據(jù)量以及數(shù)據(jù)大小
許多數(shù)據(jù)庫的元數(shù)據(jù)都是存儲(chǔ)在mysql中的,本文主要介紹了Mysql查詢數(shù)據(jù)庫或數(shù)據(jù)表中的數(shù)據(jù)量以及數(shù)據(jù)大小,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-02-02
win10下安裝mysql8.0.23 及 “服務(wù)沒有響應(yīng)控制功能”問題解決辦法
這篇文章主要介紹了win10下安裝mysql8.0.23 及 “服務(wù)沒有響應(yīng)控制功能”問題解決辦法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03

