当前位置:主页 > 数据库 > Mysql >

使用canal监控mysql数据库实现elasticsearch索引实时更新问题

时间:2022-11-03 10:29:37 | 栏目:Mysql | 点击:

业务场景

数据库变动 -> 产生binlog -> canal监控读取binlog -> 发送mq -> 索引服务消费mq -> 查询数据库 -> 更新索引 -> 消息ack

安装

下载安装

wget 地址解压即可修改配置即可启动使用wget 下载太慢了,可以自己下载下来再传到centos服务器里github1.1.5地址:https://github.com/alibaba/canal/releases/tag/canal-1.1.5

数据库启用row binlog

log-bin=mysql-bin # 开启 binlog
binlog-format=ROW # 选择 ROW 模式
server_id=1 # 配置 replaction 不要和 canal 的 slaveId 重复

建立canal授权账号

CREATE USER canal IDENTIFIED BY 'canal';  
GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'canal'@'%';
FLUSH PRIVILEGES;

使用

修改配置文件canal.properties

##################################################
######### 		    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 

配置单个连接

示例如下

#################################################
## mysql serverId , v1.0.26+ will autoGen
# canal.instance.mysql.slaveId=0
# enable gtid use true/false
canal.instance.gtidon=false
# position info 写连接即可,其他省略,会自动获取
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  先前建好的数据库用户名密码
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 只监控部分表
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 这个是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

配置多个连接

配置rabbitMQ

新建你的exchange

新建你的queue

根据前面配置的topic,作为routerkeyexchangequeue起来

程序改动

canal源码

package com.alibaba.otter.canal.connector.rabbitmq.producer;
... ... 省略
@SPI("rabbitmq")
public class CanalRabbitMQProducer extends AbstractMQProducer implements CanalMQProducer {
    // 需要监控的操作类型
    private static final String OPERATE_TYPE = "UPDATE,INSERT,DELETE";
    // 更新时,需要触发发送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"};
    // 数据处理时,需要保留的字段(需把标题等传值过去,已删除数据这些查不到了)
    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 {
            // 并发构造
            MQMessageUtils.EntryRowData[] datas = MQMessageUtils.buildMessageData(messageSub, buildExecutor);
            // 串行分区
            List<FlatMessage> flatMessages = MQMessageUtils.messageConverter(datas, messageSub.getId());
            for (FlatMessage flatMessage : flatMessages) {
                if (!OPERATE_TYPE.contains(flatMessage.getType())) {
                    continue;
                }
                // 只有设置的关键字段更新,才会触发消息发送
                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,只保留这个字段的值,其余的舍弃
                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);
                // 不需要的字段注释掉,较少网络传输消耗
                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);
        }
    }
    ... ... 省略
}

微服务消费mq

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写入性能(文本较大时,单个索引可能很大),一次处理200条,模拟剩余多少条,使用2
    private static final int BATCH_DEAL_COUNT = 2;
    // mq里待消费线程缓存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();
        // 消费前,更新剩余待消费消息数量
        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) {
            // 需要设置false,手动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());
                // 开始消费
                MessageVO messageVO = JSONObject.parseObject(str,MessageVO.class);
                log.debug("监听数据库cms_base_content表变更记录消息,消息内容: {} ", 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());
                    // 开始消费
                    MessageVO messageVO = JSONObject.parseObject(str,MessageVO.class);
                    log.debug("监听数据库cms_base_content表变更记录消息,消息内容: {} ", JSON.toJSONString(messageVO));
                    messageVOList.add(messageVO);
                }
            IIndexService indexService = SpringContextHolder.getBean(IndexServiceImpl.class);
            indexService.batchDealIndex(messageVOList, code);
            channel.basicAck(maxDeliveryTag, true);
            // Ack后,更新剩余待消费消息数量
            redisTemplate.opsForValue().set(code + "_" + WAIT_DEAL, channel.messageCount(queuName));
            System.out.println("==============>" + code + "=" + redisTemplate.opsForValue().get(code + "_" + WAIT_DEAL));
        }catch(Throwable e){
            log.error("监听前台访问记录消息,deliveryTag: {} ",maxDeliveryTag,e);
            //成功收到消息
            try {
                channel.basicNack(maxDeliveryTag,true,true);
            } catch (IOException e1) {
                log.error("ack 异常, 消息队列可能出现无法消费情况, 请及时处理",e1);
    }
    public MessageListenerBean() {
    public MessageListenerBean(String code) {
        this.code = code;
}

您可能感兴趣的文章:

相关文章