<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
資料庫變動 -> 產生binlog -> canal監控讀取binlog -> 傳送mq -> 索引服務消費mq -> 查詢資料庫 -> 更新索引 -> 訊息ack
wget 地址解壓即可修改設定即可啟動使用wget 下載太慢了,可以自己下載下來再傳到centos伺服器裡github1.1.5地址:https://github.com/alibaba/canal/releases/tag/canal-1.1.5
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.destinations = example
,預設了個examplecanal.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
,路由到不同佇列http://192.168.1.***:15672/
/
,則建立新建你的exchange
新建你的queue
根據前面設定的topic
,作為routerkey
將exchange
與queue
起來
CanalRabbitMQProducer.java
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); } } ... ... 省略 }
exchange
與queue
,消費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; }
到此這篇關於使用canal監控mysql資料庫實現elasticsearch索引實時更新的文章就介紹到這了,更多相關canal監控mysql資料庫內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45