使用canal監(jiān)控mysql數(shù)據(jù)庫(kù)實(shí)現(xiàn)elasticsearch索引實(shí)時(shí)更新問(wèn)題
業(yè)務(wù)場(chǎng)景
- 使用elasticsearch作為全文搜索引擎,對(duì)標(biāo)題、內(nèi)容等,實(shí)現(xiàn)智能搜索、輸入提示、拼音搜索等
- elasticsearch索引與數(shù)據(jù)庫(kù)數(shù)據(jù)不一致,導(dǎo)致搜索到不應(yīng)被搜到的結(jié)果,或者搜不到已有數(shù)據(jù)
- 索引相關(guān)業(yè)務(wù),影響其他業(yè)務(wù)操作,如索引刪除失敗導(dǎo)致數(shù)據(jù)庫(kù)刪除失敗
- 為了減少對(duì)現(xiàn)有業(yè)務(wù)的侵入,基于數(shù)據(jù)庫(kù)層面,對(duì)信息表進(jìn)行監(jiān)控,但需要索引的字段變動(dòng)時(shí),更新索引
- 由于使用的是mysql數(shù)據(jù)庫(kù),故決定采用alibaba的canal中間件
- 主要是監(jiān)控信息基表base,監(jiān)控這一張表的數(shù)據(jù)變動(dòng),mq消息消費(fèi)時(shí),重新從數(shù)據(jù)庫(kù)查詢數(shù)據(jù)更新或刪除索引(數(shù)據(jù)無(wú)法直接使用,要數(shù)據(jù)清洗,需要關(guān)聯(lián)查詢拼接處理等)
- 大致邏輯
數(shù)據(jù)庫(kù)變動(dòng) -> 產(chǎn)生binlog -> canal監(jiān)控讀取binlog -> 發(fā)送mq -> 索引服務(wù)消費(fèi)mq -> 查詢數(shù)據(jù)庫(kù) -> 更新索引 -> 消息ack
安裝
下載安裝
wget 地址解壓即可修改配置即可啟動(dòng)使用wget 下載太慢了,可以自己下載下來(lái)再傳到centos服務(wù)器里github1.1.5地址:https://github.com/alibaba/canal/releases/tag/canal-1.1.5
數(shù)據(jù)庫(kù)啟用row binlog
- 修改mysql數(shù)據(jù)庫(kù) my.cnf
- 開(kāi)啟 Binlog 寫(xiě)入功能,配置 binlog-format 為 ROW 模式
log-bin=mysql-bin # 開(kāi)啟 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ù)庫(kù)連接
canal.instance.master.address - 配置表過(guò)濾規(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 寫(xiě)連接即可,其他省略,會(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ù)庫(kù)用戶名密碼 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存在,沒(méi)使用默認(rèn)的
/,則創(chuàng)建

新建你的exchange

新建你的queue

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

程序改動(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)題等傳值過(guò)去,已刪除數(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);
// 判斷更新字段是否包含重要字段,不包含則跳過(guò)
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版本較低,無(wú)法使用批量消費(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寫(xiě)入性能(文本較大時(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());
// 開(kāi)始消費(fèi)
MessageVO messageVO = JSONObject.parseObject(str,MessageVO.class);
log.debug("監(jiān)聽(tīng)數(shù)據(jù)庫(kù)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());
// 開(kāi)始消費(fèi)
MessageVO messageVO = JSONObject.parseObject(str,MessageVO.class);
log.debug("監(jiān)聽(tīng)數(shù)據(jù)庫(kù)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īng)前臺(tái)訪問(wèn)記錄消息,deliveryTag: {} ",maxDeliveryTag,e);
//成功收到消息
try {
channel.basicNack(maxDeliveryTag,true,true);
} catch (IOException e1) {
log.error("ack 異常, 消息隊(duì)列可能出現(xiàn)無(wú)法消費(fèi)情況, 請(qǐng)及時(shí)處理",e1);
}
public MessageListenerBean() {
public MessageListenerBean(String code) {
this.code = code;
}
到此這篇關(guān)于使用canal監(jiān)控mysql數(shù)據(jù)庫(kù)實(shí)現(xiàn)elasticsearch索引實(shí)時(shí)更新的文章就介紹到這了,更多相關(guān)canal監(jiān)控mysql數(shù)據(jù)庫(kù)內(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ì)稱問(wèn)題解決辦法
- 如何在Elasticsearch中啟用和使用SQL功能
相關(guān)文章
MySQL數(shù)據(jù)庫(kù)的事務(wù)和索引詳解
這篇文章主要介紹了MySql 索引和事務(wù),總結(jié)分析了mysql數(shù)據(jù)庫(kù)中關(guān)于索引和事務(wù)的概念、原理、知識(shí)點(diǎn)及相關(guān)注意事項(xiàng),需要的朋友可以參考下2021-10-10
MySQL 計(jì)算時(shí)間差(分鐘)的三種實(shí)現(xiàn)
本文主要介紹了MySQL 計(jì)算時(shí)間差(分鐘)的三種實(shí)現(xiàn),包含TIMEDIFF函數(shù),TIMESTAMPDIFF函數(shù)和算術(shù)運(yùn)算符這三種方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-07-07
如何解決MySQL安裝遇到Start service紅叉問(wèn)題
在安裝MySQL時(shí),若遇到StartService步驟打紅叉無(wú)法繼續(xù),可通過(guò)計(jì)算機(jī)管理以管理員身份運(yùn)行服務(wù),找到MySQL服務(wù),更改為本地系統(tǒng)賬戶登錄,解決安裝問(wèn)題,此方法為實(shí)際操作經(jīng)驗(yàn),可供參考,確保安裝順利完成2024-10-10
Sql查詢MySql數(shù)據(jù)庫(kù)中的表名和描述表中字段(列)信息
這篇文章主要介紹了Sql查詢獲取MySql數(shù)據(jù)庫(kù)中的表名和描述表中列名數(shù)據(jù)類型,長(zhǎng)度,精度,是否可以為null,默認(rèn)值,是否自增,是否是主鍵,列描述等列信息2017-12-12
Mysql中基本語(yǔ)句優(yōu)化的十個(gè)原則小結(jié)
這篇文章主要給大家總結(jié)介紹了Mysql中基本語(yǔ)句優(yōu)化的十個(gè)原則,通過(guò)學(xué)習(xí)與記住它們,在構(gòu)造sql時(shí)可以養(yǎng)成良好的習(xí)慣,文中介紹的相對(duì)比較詳細(xì)與簡(jiǎn)單明了,需要的朋友們可以參考借鑒,下面來(lái)一起看看吧。2017-06-06
mysql插入中文數(shù)據(jù)變成問(wèn)號(hào)的解決方案
這篇文章主要介紹了mysql插入中文數(shù)據(jù)變成問(wèn)號(hào)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
深入探尋mysql自增列導(dǎo)致主鍵重復(fù)問(wèn)題的原因
前幾天開(kāi)發(fā)的同事反饋一個(gè)利用load data infile命令導(dǎo)入數(shù)據(jù)主鍵沖突的問(wèn)題,分析后確定這個(gè)問(wèn)題可能是mysql的一個(gè)bug,這里提出來(lái)給大家分享下。以免以后有童鞋遇到類似問(wèn)題百思不得其解,難以入眠,哈哈。2014-08-08
MySQL 查詢結(jié)果取交集的實(shí)現(xiàn)方法
本文將詳細(xì)介紹MySQL中如何實(shí)現(xiàn)以SQL查詢返回的結(jié)果集取交集的實(shí)現(xiàn)方法,需要的朋友可以參考2012-11-11

