canal-adapter实现mysql同步es

原始业务表数据同步

canal-admin

配置canal-admin 同步mysqlbinlog到mq中

服务器:10.246.1.248

/home/haieradmin/data/canal/canal.admin-1.1.4.tar.gz
tar -xvf canal.admin-1.1.4.tar.gz -C ./canal-admin/
vim application.yml


server:
  port: 8089
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

spring.datasource:
  address: test-mysql.rrswl.corp:3306
  database: canal_manager_yuncang
  username: root
  password: Haier_root@799
  driver-class-name: com.mysql.jdbc.Driver
  url: jdbc:mysql://${spring.datasource.address}/${spring.datasource.database}?useUnicode=true&characterEncoding=UTF-8&useSSL=false
  hikari:
    maximum-pool-size: 30
    minimum-idle: 1

canal:
  adminUser: admin
  adminPasswd: admin

sh startup.sh

访问地址:http://10.246.1.248:8089/ admin 123456

canal-deployer

采用 canal-admin配置instance

 mkdir canal-deployer
tar -xvf canal.deployer-1.1.4.tar.gz -C ./canal-deployer


vim canal_local.properties
# register ip
canal.register.ip = 10.246.1.248

# canal admin config
canal.admin.manager = 10.246.1.248:8089
canal.admin.port = 11110
canal.admin.user = admin
canal.admin.passwd = 4ACFE3202A5FF5CF467898FC58AAB1D615029441
# admin auto register
canal.admin.register.auto = true
canal.admin.register.cluster =


sh startup.sh local


cannal-instace 配置

###集群主配置

#################################################
######### 		common argument		#############
#################################################
# tcp bind ip
canal.ip = 
# register ip to zookeeper
canal.register.ip = 
canal.port = 11111
canal.metrics.pull.port = 11112
# canal instance user/passwd
#canal.user = canal
#canal.passwd = E3619321C1A937C46A0D8BD1DAC39F93B27D4458

# canal admin config
canal.admin.manager = 10.246.1.248:8089
canal.admin.port = 11110
canal.admin.user = admin
canal.admin.passwd = 4ACFE3202A5FF5CF467898FC58AAB1D615029441

canal.zkServers = 10.138.231.167:2181
# flush data to zk
canal.zookeeper.flush.period = 1000
canal.withoutNetty = false
# tcp, kafka, RocketMQ
canal.serverMode = RocketMQ
# flush meta cursor/parse position to file
canal.file.data.dir = ${canal.conf.dir}
canal.file.flush.period = 1000
## memory store RingBuffer size, should be Math.pow(2,n)
canal.instance.memory.buffer.size = 16384
## memory store RingBuffer used memory unit size , default 1kb
canal.instance.memory.buffer.memunit = 1024 
## meory store gets mode used MEMSIZE or ITEMSIZE
canal.instance.memory.batch.mode = MEMSIZE
canal.instance.memory.rawEntry = true

## detecing config
canal.instance.detecting.enable = false
#canal.instance.detecting.sql = insert into retl.xdual values(1,now()) on duplicate key update x=now()
canal.instance.detecting.sql = select 1
canal.instance.detecting.interval.time = 3
canal.instance.detecting.retry.threshold = 3
canal.instance.detecting.heartbeatHaEnable = false

# support maximum transaction size, more than the size of the transaction will be cut into multiple transactions delivery
canal.instance.transaction.size =  1024
# mysql fallback connected to new master should fallback times
canal.instance.fallbackIntervalInSeconds = 60

# network config
canal.instance.network.receiveBufferSize = 16384
canal.instance.network.sendBufferSize = 16384
canal.instance.network.soTimeout = 30

# binlog filter config
canal.instance.filter.druid.ddl = true
canal.instance.filter.query.dcl = false
canal.instance.filter.query.dml = false
canal.instance.filter.query.ddl = false
canal.instance.filter.table.error = false
canal.instance.filter.rows = false
canal.instance.filter.transaction.entry = false

# binlog format/image check
canal.instance.binlog.format = ROW,STATEMENT,MIXED 
canal.instance.binlog.image = FULL,MINIMAL,NOBLOB

# binlog ddl isolation
canal.instance.get.ddl.isolation = false

# parallel parser config
canal.instance.parser.parallel = true
## concurrent thread number, default 60% available processors, suggest not to exceed Runtime.getRuntime().availableProcessors()
#canal.instance.parser.parallelThreadSize = 16
## disruptor ringbuffer size, must be power of 2
canal.instance.parser.parallelBufferSize = 256

# table meta tsdb info
canal.instance.tsdb.enable = true
canal.instance.tsdb.dir = ${canal.file.data.dir:../conf}/${canal.instance.destination:}
canal.instance.tsdb.url = jdbc:h2:${canal.instance.tsdb.dir}/h2;CACHE_SIZE=1000;MODE=MYSQL;
canal.instance.tsdb.dbUsername = canal
canal.instance.tsdb.dbPassword = canal
# dump snapshot interval, default 24 hour
canal.instance.tsdb.snapshot.interval = 24
# purge snapshot expire , default 360 hour(15 days)
canal.instance.tsdb.snapshot.expire = 360

# aliyun ak/sk , support rds/mq
canal.aliyun.accessKey =
canal.aliyun.secretKey =

#################################################
######### 		destinations		#############
#################################################
canal.destinations =
# conf root dir
canal.conf.dir = ../conf
# auto scan instance dir add/remove and start/stop instance
canal.auto.scan = true
canal.auto.scan.interval = 5

canal.instance.tsdb.spring.xml = classpath:spring/tsdb/h2-tsdb.xml
#canal.instance.tsdb.spring.xml = classpath:spring/tsdb/mysql-tsdb.xml

canal.instance.global.mode = manager
canal.instance.global.lazy = false
canal.instance.global.manager.address = ${canal.admin.manager}
#canal.instance.global.spring.xml = classpath:spring/memory-instance.xml
#canal.instance.global.spring.xml = classpath:spring/file-instance.xml
canal.instance.global.spring.xml = classpath:spring/default-instance.xml

##################################################
######### 		     MQ 		     #############
##################################################
canal.mq.servers = mq.haier.net:9876
canal.mq.retries = 0
canal.mq.batchSize = 16384
canal.mq.maxRequestSize = 1048576
canal.mq.lingerMs = 100
canal.mq.bufferMemory = 33554432
canal.mq.canalBatchSize = 50
canal.mq.canalGetTimeout = 100
canal.mq.flatMessage = true
canal.mq.compressionType = none
canal.mq.acks = all
#canal.mq.properties. =
canal.mq.producerGroup = yuncang_es_test_group
# Set this value to "cloud", if you want open message trace feature in aliyun.
canal.mq.accessChannel = local
# aliyun mq namespace
#canal.mq.namespace =

##################################################
#########     Kafka Kerberos Info    #############
##################################################
canal.mq.kafka.kerberos.enable = false
canal.mq.kafka.kerberos.krb5FilePath = "../conf/kerberos/krb5.conf"
canal.mq.kafka.kerberos.jaasFilePath = "../conf/kerberos/jaas.conf"

instance配置

#################################################
## 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=test-mysql.rrswl.corp: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=root
canal.instance.dbPassword=Haier_root@799
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=yuncang_order01.yc_order
# table black regex
canal.instance.filter.black.regex=
# table field filter(format: schema1.tableName1:field1/field2,schema2.tableName2:field1/field2)
canal.instance.filter.field=yuncang_order01.yc_order:id/order_code/order_status
# 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
canal.mq.topic=yuncang_esmq_test
# dynamic topic route by schema or table regex
#canal.mq.dynamicTopic=mytest1.user,mytest2\\..*,.*\\..*
canal.mq.partition=0
# hash partition config
canal.mq.partitionsNum=10
#canal.mq.partitionHash=test.table:id^name,.*\\..*
canal.mq.partitionHash=yuncang_order01.yc_order:order_code
#################################################



过滤表 和字段

canal.instance.filter.regex=yuncang_order01.yc_order

canal.instance.filter.field=yuncang_order01.yc_order:id/order_code/order_status

topic 根据分片键分区

canal.mq.partition=0
canal.mq.partitionsNum=10
canal.mq.partitionHash=yuncang_order01.yc_order:order_code

mq顺序性问题

 1.canal目前选择支持的kafka/rocketmq,本质上都是基于本地文件的方式来支持了分区级的顺序消息的能力,也就是binlog写入mq是可以有一些顺序性保障,这个取决于用户的一些参数选择

 2.canal支持MQ数据的几种路由方式:单topic单分区,单topic多分区、多topic单分区、多topic多分区
canal.mq.dynamicTopic,主要控制是否是单topic还是多topic,针对命中条件的表可以发到表名对应的topic、库名对应的topic、默认topic name
canal.mq.partitionsNum、canal.mq.partitionHash,主要控制是否多分区以及分区的partition的路由计算,针对命中条件的可以做到按表级做分区、pk级做分区等

 3.canal的消费顺序性,主要取决于描述2中的路由选择,举例说明:
单topic单分区,可以严格保证和binlog一样的顺序性,缺点就是性能比较慢,单分区的性能写入大概在2~3k的TPS
多topic单分区,可以保证表级别的顺序性,一张表或者一个库的所有数据都写入到一个topic的单分区中,可以保证有序性,针对热点表也存在写入分区的性能问题
单topic、多topic的多分区,如果用户选择的是指定table的方式,那和第二部分一样,保障的是表级别的顺序性(存在热点表写入分区的性能问题),如果用户选择的是指定pk hash的方式,那只能保障的是一个pk的多次binlog顺序性 ** pk hash的方式需要业务权衡,这里性能会最好,但如果业务上有pk变更或者对多pk数据有顺序性依赖,就会产生业务处理错乱的情况. 如果有pk变更,pk变更前和变更后的值会落在不同的分区里,业务消费就会有先后顺序的问题,需要注意


canal.mq.partitionHash 表达式说明
canal 1.1.3版本之后, 支持配置格式:schema.table:pk1^pk2,多个配置之间使用逗号分隔

例子1:test\\.test:pk1^pk2 指定匹配的单表,对应的hash字段为pk1 + pk2
例子2:.*\\..*:id 正则匹配,指定所有正则匹配的表对应的hash字段为id
例子3:.*\\..*:$pk$ 正则匹配,指定所有正则匹配的表对应的hash字段为表主键(自动查找)
例子4: 匹配规则啥都不写,则默认发到0这个partition上
例子5:.*\\..* ,不指定pk信息的正则匹配,将所有正则匹配的表,对应的hash字段为表名
按表hash: 一张表的所有数据可以发到同一个分区,不同表之间会做散列 (会有热点表分区过大问题)
例子6: test\\.test:id,.\\..* , 针对test的表按照id散列,其余的表按照table散列
注意:大家可以结合自己的业务需求,设置匹配规则,多条匹配规则之间是按照顺序进行匹配(命中一条规则就返回)

更新数据比较

{
	"data": [{
		"id": "1",
		"order_code": "21",
		"order_status": "12323"
	}],
	"database": "yuncang_order01",
	"es": 1614158010000,
	"id": 14,
	"isDdl": false,
	"mysqlType": {
		"id": "bigint(20)",
		"order_code": "varchar(50)",
		"order_status": "varchar(10)"
	},
	"old": null,
	"pkNames": ["id"],
	"sql": "",
	"sqlType": {
		"id": -5,
		"order_code": 12,
		"order_status": 12
	},
	"table": "yc_order",
	"ts": 1614158010946,
	"type": "UPDATE"
}


如果有更新
{
	"data": [{
		"id": "1",
		"order_code": "21",
		"order_status": "abc"
	}],
	"database": "yuncang_order01",
	"es": 1614158022000,
	"id": 16,
	"isDdl": false,
	"mysqlType": {
		"id": "bigint(20)",
		"order_code": "varchar(50)",
		"order_status": "varchar(10)"
	},
	"old": [{
		"order_status": "12323"
	}],
	"pkNames": ["id"],
	"sql": "",
	"sqlType": {
		"id": -5,
		"order_code": 12,
		"order_status": 12
	},
	"table": "yc_order",
	"ts": 1614158022369,
	"type": "UPDATE"
}

无更新: 	"old": null,

消费类处理思路

  1. 判断 “type”: “UPDATE” 更新 insert新增
  2. update时 判断 “old”: null 是否为空
  3. 不为空,根据 old 条件修改 新数据
  4. 判断修改值,更新结果为0时 ,将原信息发送异常队列
  5. 更新数为1 则正常结束

工程代码

http://

大宽表同步es

instance配置


# table regex
canal.instance.filter.regex=yuncang_order01.yc_order_mapping,yuncang_order02.yc_order_mapping
# table black regex
canal.instance.filter.black.regex=
# table field filter(format: schema1.tableName1:field1/field2,schema2.tableName2:field1/field2)
# 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
canal.mq.topic=yuncang_ordermap_esmq_test
# dynamic topic route by schema or table regex
#canal.mq.dynamicTopic=mytest1.user,mytest2\\..*,.*\\..*
canal.mq.partition=0
# hash partition config
canal.mq.partitionsNum=10
#canal.mq.partitionHash=test.table:id^name,.*\\..*
canal.mq.partitionHash=yuncang_order0

canal-adapter

vim application.yml

canal.conf:
  mode: rocketMQ
 # canalServerHost: 10.138.227.111:11111
 # zookeeperHosts: 10.138.231.167:2181
  mqServers: mq.haier.net:9876
#  flatMessage: true
  batchSize: 500
  syncBatchSize: 1000
  retries: 0
  timeout:
  accessKey:
  secretKey:
  srcDataSources:
    defaultDS:
      url: jdbc:mysql://3306order01?useUnicode=true
      username:
      password: 
    defaultDS2:
      url: jdbc:mysql://:3306/order02?useUnicode=true
      username: 
      password: 

  - instance: yuncang_ordermap_esmq_test
    groups:
    - groupId: yuncang_ordermap_esmq_test_group
      outerAdapters:
      - name: es7
        hosts: 
        #key: esConf
        properties:
          mode: rest
         
          cluster.name: wlelk-es

 vim yuncang_mapper01.yml
 
dataSourceKey: defaultDS1        # 源数据源的key, 对应上面配置的srcDataSources中的值
#outerAdapterKey: esConf         # 对应application.yml中es配置的key
destination: yuncang_ordermap_esmq_test      # cannal的instance或者MQ的topic
groupId: yuncang_ordermap_esmq_test_group      # 对应MQ模式下的groupId, 只会同步对应groupId的数据
esMapping:
  _index: yc_order_mapping_es           # es 的索引名称
  _type: _doc                   # es 的type名称, es7下无需配置此项
  _id: id                      # es 的_id, 如果不配置该项必须配置下面的pk项_id则会由es自动分配
#  pk: id                       # 如果不需要_id, 则需要指定一个属性为主键属性
  # sql映射
  sql: "select id, order_id, order_code, source_first_orderno, whdoc_no, whdoc_type, exp_no, product_code, product_name, pg_code, receiver_wh_code, receiver_center_code, shipper_wh_code, shipper_center_code, owner_code, order_status, order_biz_type, order_date, deleted, creater, create_date, updater, update_date, add1, add2, add3 from yc_order_mapping a "
#  objFields:
#    _labels: array:;           # 数组或者对象属性, array:; 代表以;字段里面是以;分隔的
#    _obj: object               # json对象
  etlCondition: "where a.create_date>={} and a.create_date <{}"      # etl 的条件参数
  commitBatch: 5000                         # 提交批大小

###canal-admin 控制台
canal-adapter实现mysql同步es_第1张图片
canal-adapter实现mysql同步es_第2张图片

你可能感兴趣的:(数据同步,mysql,elasticsearch)