欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用canal監(jiān)控mysql數(shù)據(jù)庫(kù)實(shí)現(xiàn)elasticsearch索引實(shí)時(shí)更新問(wèn)題

 更新時(shí)間:2022年03月29日 14:07:58   作者:堅(jiān)持是一種態(tài)度  
這篇文章主要介紹了使用canal監(jiān)控mysql數(shù)據(jù)庫(kù)實(shí)現(xiàn)elasticsearch索引實(shí)時(shí)更新,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

業(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,作為routerkeyexchangequeue起來(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è)置好的exchangequeue,消費(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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論