业务场景

  • 使用elasticsearch作为全文搜索引擎,对标题、内容等,实现智能搜索、输入提示、拼音搜索等
  • elasticsearch索引与数据库数据不一致,导致搜索到不应被搜到的结果,或者搜不到已有数据
  • 索引相关业务,影响其他业务操作,如索引删除失败导致数据库删除失败
  • 为了减少对现有业务的侵入,基于数据库层面,对信息表进行监控,但需要索引的字段变动时,更新索引
  • 由于使用的是mysql数据库,故决定采用alibaba的canal中间件
  • 主要是监控信息基表base,监控这一张表的数据变动,mq消息消费时,重新从数据库查询数据更新或删除索引(数据无法直接使用,要数据清洗,需要关联查询拼接处理等)
  • 大致逻辑

数据库变动 -> 产生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

  • 修改mysql数据库 my.cnf
  • 开启 binlog 写入功能,配置 binlog-format 为 row 模式
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

  • 主配置文件canal.properties
  • 配置你的连接canal.destinations = example,默认了个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 

配置单个连接

  • canal/conf/
  • 修改instance.properties
  • 需要配置数据库连接canal.instance.master.address
  • 配置表过滤规则,canal.instance.filter.regex,注意.\\
  • 配置路由规则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 写连接即可,其他省略,会自动获取
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

配置多个连接

  • conf下新建文件夹,复制一份instance.properties
  • canal.destinations里添加上面的文件夹名称
  • 可以使用不同的canal.mq.topic,路由到不同队列

配置rabbitmq

  • 登入你的rabbitmq管理界面http://192.168.1.***:15672/
  • 确保用户存在,且有权限
  • 确保vhost存在,没使用默认的/,则创建

新建你的exchange

新建你的queue

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

程序改动

canal源码

  • 修改canalrabbitmqproducer.java
  • 实现只监控部分字段
  • 处理mq消息体,去除不需要的东西,减少数据传输
  • 主要修改了send(mqdestination canaldestination, string topicname, message messagesub)
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

  • 根据前面的mq配置,建立rabbitmq连接
  • 根据前面设置好的exchangequeue,消费mq即可
  • 更新或删除索引
  • ack确认索引更新失败的,根据情况,nack或者存入失败表
  • 由于使用的springboot版本较低,无法使用批量消费接口,只好使用拉模式,主动消费了
  • 部分代码
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;
}

到此这篇关于使用canal监控mysql数据库实现elasticsearch索引实时更新的文章就介绍到这了,更多相关canal监控mysql数据库内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!