mirror of
https://github.com/alibaba/canal.git
synced 2026-11-04 00:30:15 +08:00
Compare commits
154 Commits
canal-1.1.
...
canal-1.1.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
774aeeea68 | ||
|
|
f28efce11e | ||
|
|
d03e7e2b15 | ||
|
|
56ed158814 | ||
|
|
166a9a7f8f | ||
|
|
b131e8cfa4 | ||
|
|
2e1d0e36c5 | ||
|
|
ddcf619deb | ||
|
|
8f1b66ab5a | ||
|
|
167858cd95 | ||
|
|
04e56fb94c | ||
|
|
00fce30072 | ||
|
|
423392a18a | ||
|
|
cdb34571ab | ||
|
|
3b4d28eec3 | ||
|
|
297122f47f | ||
|
|
f9ff05f16c | ||
|
|
071545987b | ||
|
|
c36a51b8e3 | ||
|
|
232bbaf6d4 | ||
|
|
a0b38a9cac | ||
|
|
d76367584c | ||
|
|
86fd77f9c4 | ||
|
|
ebaf78f5aa | ||
|
|
b484593869 | ||
|
|
a7bf6258f7 | ||
|
|
2c6bd3ee1b | ||
|
|
87ac3daecc | ||
|
|
fd7b9d766a | ||
|
|
f822761ab2 | ||
|
|
1e2cf9d476 | ||
|
|
2d930894ff | ||
|
|
30b7de7233 | ||
|
|
0d22dbc982 | ||
|
|
8446e17703 | ||
|
|
fb936f896e | ||
|
|
0d0fcbbc0b | ||
|
|
5cfbc6b91d | ||
|
|
3b1f6ce4fb | ||
|
|
fd3927ce3e | ||
|
|
bbfd4b4996 | ||
|
|
848cbe11dd | ||
|
|
f7185a618b | ||
|
|
d70dc8b88c | ||
|
|
b5f5d3f0f0 | ||
|
|
ddfc2464f3 | ||
|
|
c3402a97f3 | ||
|
|
6ee6b3c398 | ||
|
|
42a4abe4c7 | ||
|
|
0f1334c92c | ||
|
|
346d091d00 | ||
|
|
27dba9ec1b | ||
|
|
8dbf63e436 | ||
|
|
30a11c75cb | ||
|
|
49caff5759 | ||
|
|
0a7251add0 | ||
|
|
b5dac60cbb | ||
|
|
9270834631 | ||
|
|
575dd59c78 | ||
|
|
15e79c1400 | ||
|
|
c75c248086 | ||
|
|
741f6310b3 | ||
|
|
2202ec451a | ||
|
|
1830458b6b | ||
|
|
1b88430f71 | ||
|
|
bbb4c4347e | ||
|
|
0ee46ad70e | ||
|
|
243e129710 | ||
|
|
a91f204682 | ||
|
|
5bc5eec85e | ||
|
|
80d3781d81 | ||
|
|
b1e2ab4448 | ||
|
|
3e49e33f9f | ||
|
|
986840b6bf | ||
|
|
61aea888f6 | ||
|
|
c16037122b | ||
|
|
a823b909ad | ||
|
|
5d55c7ac00 | ||
|
|
75f380252e | ||
|
|
5eb67990ca | ||
|
|
017fe87e4b | ||
|
|
fc050c3ce9 | ||
|
|
b893aafae7 | ||
|
|
9c24b26d02 | ||
|
|
22d1fc98ee | ||
|
|
d88f204a15 | ||
|
|
5d0f79932a | ||
|
|
7c44e5933d | ||
|
|
4d36c60738 | ||
|
|
53c2a02124 | ||
|
|
1701a4c97c | ||
|
|
e4b6385dcc | ||
|
|
2e92ec3e4d | ||
|
|
d20485027f | ||
|
|
eb2a83b975 | ||
|
|
9344ed121f | ||
|
|
c3327e567e | ||
|
|
3ed8987779 | ||
|
|
fa8588f766 | ||
|
|
fa8ffb8e66 | ||
|
|
9da8f9cc5a | ||
|
|
af03f07cc7 | ||
|
|
5ae16b1c7c | ||
|
|
a37a7ff142 | ||
|
|
ff592758cf | ||
|
|
b04446d24d | ||
|
|
40f8c931c7 | ||
|
|
a22517adc2 | ||
|
|
821f3eced5 | ||
|
|
00ec70d425 | ||
|
|
9d48d23787 | ||
|
|
9535e82da6 | ||
|
|
fd80f953e9 | ||
|
|
05718a9f20 | ||
|
|
19b7f730b6 | ||
|
|
4f2b4cea53 | ||
|
|
e566160f1e | ||
|
|
74890050d0 | ||
|
|
0cda90cdea | ||
|
|
1a11153cd2 | ||
|
|
d5aa324ce4 | ||
|
|
09df602f3b | ||
|
|
b026c44ea8 | ||
|
|
19f765df77 | ||
|
|
4e1675033a | ||
|
|
e9439125bd | ||
|
|
a11f9e4b34 | ||
|
|
10b0ade627 | ||
|
|
1a8d6e65cf | ||
|
|
9748fceda8 | ||
|
|
7005c11ac2 | ||
|
|
88bf2ae64d | ||
|
|
cae6df1457 | ||
|
|
6682c56b9f | ||
|
|
5394613ba6 | ||
|
|
6e84b98651 | ||
|
|
af1a6a851f | ||
|
|
1516cf779d | ||
|
|
db56effd91 | ||
|
|
f3d1c8b754 | ||
|
|
abf6a37f3a | ||
|
|
e8e0032404 | ||
|
|
52734eac7e | ||
|
|
ca61be5f5a | ||
|
|
b28e3d6f18 | ||
|
|
1ab1f119b8 | ||
|
|
a332f23b11 | ||
|
|
a6798c61df | ||
|
|
8ae8f526a6 | ||
|
|
847634a0f2 | ||
|
|
bc8f201b21 | ||
|
|
e450c3f83f | ||
|
|
32910b5983 | ||
|
|
a497962153 |
61
README.md
61
README.md
@@ -1,14 +1,6 @@
|
|||||||
<div class="blog_content">
|
<div class="blog_content">
|
||||||
<div class="iteye-blog-content-contain">
|
<div class="iteye-blog-content-contain">
|
||||||
|
|
||||||
<h3>最新更新</h3>
|
|
||||||
<ol>
|
|
||||||
<li>canal QQ讨论群已经建立,群号:161559791 ,欢迎加入进行技术讨论。</li>
|
|
||||||
<li>canal消费端项目开源: Otter(分布式数据库同步系统),地址:<a href="https://github.com/alibaba/otter">https://github.com/alibaba/otter</a></li>
|
|
||||||
<li>Canal已在阿里云推出商业化版本 <a href="https://www.aliyun.com/product/dts?spm=a2c4g.11186623.cloudEssentials.80.srdwr7">数据传输服务DTS</a>, 开通即用,免去部署维护的昂贵使用成本。DTS针对阿里云RDS、DRDS等产品进行了适配,解决了Binlog日志回收,主备切换、VPC网络切换等场景下的订阅高可用问题。同时,针对RDS进行了针对性的性能优化。出于稳定性、性能及成本的考虑,强烈推荐阿里云用户使用DTS产品。<a href="https://help.aliyun.com/document_detail/26592.html?spm=a2c4g.11174283.6.539.t1Y91E">DTS产品使用文档</a></li>
|
|
||||||
DTS支持阿里云RDS&DRDS的Binlog日志实时订阅,现推出首月免费体验,限时限量,<a href="https://common-buy.aliyun.com/?commodityCode=dtspre&request=%7b%22dts_function%22%3a%22data_subscribe%22%7d">立即体验>>></a>
|
|
||||||
</ol>
|
|
||||||
|
|
||||||
<h1>背景</h1>
|
<h1>背景</h1>
|
||||||
<p style="font-size: 14px;"> 早期,阿里巴巴B2B公司因为存在杭州和美国双机房部署,存在跨机房同步的业务需求。不过早期的数据库同步业务,主要是基于trigger的方式获取增量变更,不过从2010年开始,阿里系公司开始逐步的尝试基于数据库的日志解析,获取增量变更进行同步,由此衍生出了增量订阅&消费的业务,从此开启了一段新纪元。</p>
|
<p style="font-size: 14px;"> 早期,阿里巴巴B2B公司因为存在杭州和美国双机房部署,存在跨机房同步的业务需求。不过早期的数据库同步业务,主要是基于trigger的方式获取增量变更,不过从2010年开始,阿里系公司开始逐步的尝试基于数据库的日志解析,获取增量变更进行同步,由此衍生出了增量订阅&消费的业务,从此开启了一段新纪元。</p>
|
||||||
<p style="font-size: 14px;"> ps. 目前内部版本已经支持mysql和oracle部分版本的日志解析,当前的canal开源版本支持5.7及以下的版本(阿里内部mysql 5.7.13, 5.6.10, mysql 5.5.18和5.1.40/48)</p>
|
<p style="font-size: 14px;"> ps. 目前内部版本已经支持mysql和oracle部分版本的日志解析,当前的canal开源版本支持5.7及以下的版本(阿里内部mysql 5.7.13, 5.6.10, mysql 5.5.18和5.1.40/48)</p>
|
||||||
@@ -46,6 +38,16 @@ DTS支持阿里云RDS&DRDS的Binlog日志实时订阅,现推出首月免费体
|
|||||||
<li>canal解析binary log对象(原始为byte流)</li>
|
<li>canal解析binary log对象(原始为byte流)</li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
|
<h1>重要版本更新说明</h1>
|
||||||
|
|
||||||
|
canal 1.1.x系列,参考release文档:<a href="https://github.com/alibaba/canal/releases">版本发布信息</a>
|
||||||
|
|
||||||
|
1. 整体性能测试&优化,提升了150%. #726 参考: 【[Performance](https://github.com/alibaba/canal/wiki/Performance)】
|
||||||
|
2. 原生支持prometheus监控 #765 【[Prometheus QuickStart](https://github.com/alibaba/canal/wiki/Prometheus-QuickStart)】
|
||||||
|
3. 原生支持kafka消息投递 #695 【[Canal Kafka/RocketMQ QuickStart](https://github.com/alibaba/canal/wiki/Canal-Kafka-RocketMQ-QuickStart)】
|
||||||
|
4. 原生支持aliyun rds的binlog订阅 (解决自动主备切换/oss binlog离线解析) 参考: 【[Aliyun RDS QuickStart](https://github.com/alibaba/canal/wiki/aliyun-RDS-QuickStart)】
|
||||||
|
5. 原生支持docker镜像 #801 参考: 【[Docker QuickStart](https://github.com/alibaba/canal/wiki/Docker-QuickStart)】
|
||||||
|
|
||||||
<h1>相关文档</h1>
|
<h1>相关文档</h1>
|
||||||
|
|
||||||
See the wiki page for : <a href="https://github.com/alibaba/canal/wiki" >wiki文档</a>
|
See the wiki page for : <a href="https://github.com/alibaba/canal/wiki" >wiki文档</a>
|
||||||
@@ -54,20 +56,41 @@ See the wiki page for : <a href="https://github.com/alibaba/canal/wiki" >wiki文
|
|||||||
<ul>
|
<ul>
|
||||||
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/Home">Home</a></li>
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/Home">Home</a></li>
|
||||||
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/Introduction">Introduction</a></li>
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/Introduction">Introduction</a></li>
|
||||||
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/QuickStart">QuickStart</a></li>
|
<li>
|
||||||
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/ClientExample">ClientExample</a></li>
|
<a class="internal present" href="https://github.com/alibaba/canal/wiki/QuickStart">QuickStart</a>
|
||||||
|
<ul>
|
||||||
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/Docker-QuickStart">Docker QuickStart</a></li>
|
||||||
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/Canal-Kafka-RocketMQ-QuickStart">Canal Kafka/RocketMQ QuickStart</a></li>
|
||||||
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/aliyun-RDS-QuickStart">Aliyun RDS QuickStart</a></li>
|
||||||
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/Prometheus-QuickStart">Prometheus QuickStart</a></li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/AdminGuide">AdminGuide</a></li>
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/AdminGuide">AdminGuide</a></li>
|
||||||
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/ClientExample">ClientExample</a></li>
|
||||||
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/ClientAPI">ClientAPI</a></li>
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/ClientAPI">ClientAPI</a></li>
|
||||||
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/Performance">Performance</a></li>
|
||||||
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/DevGuide">DevGuide</a></li>
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/DevGuide">DevGuide</a></li>
|
||||||
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/BinlogChange%28mysql5.6%29">BinlogChange(Mysql5.6)</a></li>
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/BinlogChange%28mysql5.6%29">BinlogChange(Mysql5.6)</a></li>
|
||||||
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/BinlogChange%28MariaDB%29">BinlogChange(MariaDB)</a></li>
|
||||||
|
<li><a class="internal present" href="https://github.com/alibaba/canal/wiki/TableMetaTSDB">TableMetaTSDB</a></li>
|
||||||
<li><a href="http://alibaba.github.com/canal/release.html">ReleaseNotes</a></li>
|
<li><a href="http://alibaba.github.com/canal/release.html">ReleaseNotes</a></li>
|
||||||
<li><a href="https://github.com/alibaba/canal/releases">Download</a></li>
|
<li><a href="https://github.com/alibaba/canal/releases">Download</a></li>
|
||||||
|
<li><a class="internal present" href="/alibaba/canal/wiki/FAQ">FAQ</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
|
<h1>多语言业务</h1>
|
||||||
|
|
||||||
|
1. canal整体交互协议设计上使用了protobuf3.0,理论上可以支持绝大部分的多语言场景,欢迎大家提交多客户端的PR
|
||||||
|
* canal java客户端: <a href="https://github.com/alibaba/canal/wiki/ClientExample"> https://github.com/alibaba/canal/wiki/ClientExample </a>
|
||||||
|
* canal c#客户端开源项目地址:<a href="https://github.com/CanalClient/CanalSharp"> https://github.com/CanalSharp/CanalSharp </a>
|
||||||
|
* canal go客户端开源项目地址:<a href="https://github.com/CanalClient/canal-go"> https://github.com/CanalClient/canal-go </a>
|
||||||
|
2. canal作为MySQL binlog的增量获取工具,可以将数据投递到MQ系统中,比如Kafka/RocketMQ,可以借助于MQ的多语言能力
|
||||||
|
* 参考文档: [Canal Kafka/RocketMQ QuickStart](https://github.com/alibaba/canal/wiki/Canal-Kafka-RocketMQ-QuickStart)
|
||||||
|
|
||||||
<h1>相关资料</h1>
|
<h1>相关资料</h1>
|
||||||
|
|
||||||
* ADC阿里技术嘉年华分享ppt (放在google docs上,可能需要翻墙): <a href="https://docs.google.com/presentation/d/1MkszUPYRDkfVPz9IqOT1LLT5d9tuwde_WC8GZvjaDRg/edit?usp=sharing">ppt下载</href>
|
* ADC阿里技术嘉年华分享ppt (放在google docs上,可能需要翻墙): <a href="https://docs.google.com/presentation/d/1MkszUPYRDkfVPz9IqOT1LLT5d9tuwde_WC8GZvjaDRg/edit?usp=sharing">ppt下载</href>
|
||||||
* [与阿里巴巴的RocketMQ配合使用](https://github.com/alibaba/RocketMQ)
|
* [与阿里巴巴的RocketMQ配合使用](https://github.com/apache/RocketMQ)
|
||||||
|
|
||||||
<h1>相关开源</h1>
|
<h1>相关开源</h1>
|
||||||
<ol>
|
<ol>
|
||||||
@@ -91,9 +114,13 @@ See the wiki page for : <a href="https://github.com/alibaba/canal/wiki" >wiki文
|
|||||||
<li>报告issue:<a href="https://github.com/alibaba/canal/issues">issues</a></li>
|
<li>报告issue:<a href="https://github.com/alibaba/canal/issues">issues</a></li>
|
||||||
</ol>
|
</ol>
|
||||||
|
|
||||||
<pre>
|
<h3>最新更新</h3>
|
||||||
【招聘】阿里巴巴中间件团队招聘JAVA高级工程师
|
<ol>
|
||||||
岗位主要为技术型内容(非业务部门),阿里中间件整个体系对于未来想在技术上有所沉淀的同学还是非常有帮助的
|
<li>canal发布重大版本更新1.1.0,具体releaseNode参考:<a href="https://github.com/alibaba/canal/releases/tag/canal-1.1.0">https://github.com/alibaba/canal/releases/tag/canal-1.1.0</a></li>
|
||||||
工作地点:杭州、北京均可. ps. 阿里待遇向来都是不错的,有意者可以QQ、微博私聊.
|
<li>canal c#客户端开源项目地址:<a href="https://github.com/CanalClient/CanalSharp"> https://github.com/CanalClient/CanalSharp </a>,推荐! </li>
|
||||||
具体招聘内容:https://job.alibaba.com/zhaopin/position_detail.htm?positionId=32666
|
<li>canal QQ讨论群已经建立,群号:161559791 ,欢迎加入进行技术讨论。</li>
|
||||||
</pre>
|
<li>canal消费端项目开源: Otter(分布式数据库同步系统),地址:<a href="https://github.com/alibaba/otter">https://github.com/alibaba/otter</a></li>
|
||||||
|
|
||||||
|
<li>Canal已在阿里云推出商业化版本 <a href="https://www.aliyun.com/product/dts?spm=a2c4g.11186623.cloudEssentials.80.srdwr7">数据传输服务DTS</a>, 开通即用,免去部署维护的昂贵使用成本。DTS针对阿里云RDS、DRDS等产品进行了适配,解决了Binlog日志回收,主备切换、VPC网络切换等场景下的订阅高可用问题。同时,针对RDS进行了针对性的性能优化。出于稳定性、性能及成本的考虑,强烈推荐阿里云用户使用DTS产品。<a href="https://help.aliyun.com/document_detail/26592.html?spm=a2c4g.11174283.6.539.t1Y91E">DTS产品使用文档</a></li>
|
||||||
|
DTS支持阿里云RDS&DRDS的Binlog日志实时订阅,现推出首月免费体验,限时限量,<a href="https://common-buy.aliyun.com/?commodityCode=dtspre&request=%7b%22dts_function%22%3a%22data_subscribe%22%7d">立即体验>>></a>
|
||||||
|
</ol>
|
||||||
|
|||||||
251
client-adapter/README.md
Normal file
251
client-adapter/README.md
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
## 基本说明
|
||||||
|
canal 1.1.1版本之后, 增加客户端数据落地的适配及启动功能, 目前支持功能:
|
||||||
|
* 客户端启动器
|
||||||
|
* 同步管理REST接口
|
||||||
|
* 日志适配器, 作为DEMO
|
||||||
|
* HBase的数据同步(表对表同步), ETL功能
|
||||||
|
* (后续支持) ElasticSearch多表数据同步,ETL功能
|
||||||
|
|
||||||
|
## 环境版本
|
||||||
|
* 操作系统:无要求
|
||||||
|
* java版本: jdk1.8 以上
|
||||||
|
* canal 版本: 请下载最新的安装包,本文以当前v1.1.1 的canal.deployer-1.1.1.tar.gz为例
|
||||||
|
* MySQL版本 :5.7.18
|
||||||
|
* HBase版本: Apache HBase 1.1.2, 若和服务端版本不一致可自行替换客户端HBase依赖
|
||||||
|
|
||||||
|
## 一、适配器启动器
|
||||||
|
client-adapter分为适配器和启动器两部分, 适配器为多个fat jar, 每个适配器会将自己所需的依赖打成一个包, 以SPI的方式让启动器动态加载
|
||||||
|
|
||||||
|
|
||||||
|
启动器为 SpringBoot 项目, 支持canal-client启动的同时提供相关REST管理接口, 运行目录结构为:
|
||||||
|
```
|
||||||
|
canal-adapter-launcher.jar
|
||||||
|
- lib
|
||||||
|
client-adapter.logger-1.1.1-jar-with-dependencies.jar
|
||||||
|
client-adapter.hbase-1.1.1-jar-with-dependencies.jar
|
||||||
|
- config
|
||||||
|
application.yml
|
||||||
|
- hbase
|
||||||
|
mytest_person2.yml
|
||||||
|
```
|
||||||
|
以上目录结构最终会打包成 canal-adapter-launcher.tar.gz 压缩包
|
||||||
|
|
||||||
|
## 二、启动器
|
||||||
|
### 2.1 启动器配置 application.yml
|
||||||
|
#### canal相关配置部分说明
|
||||||
|
```
|
||||||
|
canal.conf:
|
||||||
|
canalServerHost: 127.0.0.1:11111 # 对应单机模式下的canal server的ip:port
|
||||||
|
zookeeperHosts: slave1:2181 # 对应集群模式下的zk地址, 如果配置了canalServerHost, 则以canalServerHost为准
|
||||||
|
bootstrapServers: slave1:6667 # kafka或rocketMQ地址, 与canalServerHost不能并存
|
||||||
|
flatMessage: true # 扁平message开关, 是否以json字符串形式投递数据, 仅在kafka/rocketMQ模式下有效
|
||||||
|
canalInstances: # canal实例组, 如果是tcp模式可配置此项
|
||||||
|
- instance: example # 对应canal destination
|
||||||
|
groups: # 对应适配器分组, 分组间的适配器并行运行
|
||||||
|
- outAdapters: # 适配器列表, 分组内的适配串行运行
|
||||||
|
- name: logger # 适配器SPI名
|
||||||
|
- name: hbase
|
||||||
|
properties: # HBase相关连接参数
|
||||||
|
hbase.zookeeper.quorum: slave1
|
||||||
|
hbase.zookeeper.property.clientPort: 2181
|
||||||
|
zookeeper.znode.parent: /hbase
|
||||||
|
mqTopics: # MQ topic租, 如果是kafka或者rockeMQ模式可配置此项, 与canalInstances不能并存
|
||||||
|
- mqMode: kafka # MQ的模式: kafak/rocketMQ
|
||||||
|
topic: example # MQ topic
|
||||||
|
groups: # group组
|
||||||
|
- groupId: g2 # group id
|
||||||
|
outAdapters: # 适配器列表, 以下配置和canalInstances中一样
|
||||||
|
- name: logger
|
||||||
|
```
|
||||||
|
#### 适配器相关配置部分说明
|
||||||
|
```
|
||||||
|
adapter.conf:
|
||||||
|
datasourceConfigs: # 数据源配置列表, 数据源将在适配器中用于ETL、数据同步回查等使用
|
||||||
|
defaultDS: # 数据源 dataSourceKey, 适配器中通过该值获取指定数据源
|
||||||
|
url: jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true
|
||||||
|
username: root
|
||||||
|
password: 121212
|
||||||
|
adapterConfigs: # 适配器内部配置列表
|
||||||
|
- hbase/mytest_person2.yml # 类型/配置文件名, 这里示例就是对应HBase适配器hbase目录下的mytest_person2.yml文件
|
||||||
|
```
|
||||||
|
## 2.2 同步管理REST接口
|
||||||
|
#### 2.2.1 查询所有订阅同步的canal destination或MQ topic
|
||||||
|
```
|
||||||
|
curl http://127.0.0.1:8081/destinations
|
||||||
|
```
|
||||||
|
#### 2.2.2 数据同步开关
|
||||||
|
```
|
||||||
|
curl http://127.0.0.1:8081/syncSwitch/example/off -X PUT
|
||||||
|
```
|
||||||
|
针对 example 这个canal destination/MQ topic 进行开关操作. off代表关闭, 该destination/topic下的同步将阻塞或者断开连接不再接收数据, on代表开启
|
||||||
|
|
||||||
|
注: 如果在配置文件中配置了 zookeeperHosts 项, 则会使用分布式锁来控制HA中的数据同步开关, 如果是单机模式则使用本地锁来控制开关
|
||||||
|
#### 2.2.3 数据同步开关状态
|
||||||
|
```
|
||||||
|
curl http://127.0.0.1:8081/syncSwitch/example
|
||||||
|
```
|
||||||
|
查看指定 canal destination/MQ topic 的数据同步开关状态
|
||||||
|
#### 2.2.4 手动ETL
|
||||||
|
```
|
||||||
|
curl http://127.0.0.1:8081/etl/hbase/mytest_person2.yml -X POST -d "params=2018-10-21 00:00:00"
|
||||||
|
```
|
||||||
|
导入数据到指定类型的库
|
||||||
|
#### 2.2.5 查看相关库总数据
|
||||||
|
```
|
||||||
|
curl http://127.0.0.1:8081/count/hbase/mytest_person2.yml
|
||||||
|
```
|
||||||
|
### 2.3 启动canal-adapter示例
|
||||||
|
#### 2.3.1 启动canal server (单机模式), 参考: [Canal QuickStart](https://github.com/alibaba/canal/wiki/QuickStart)
|
||||||
|
#### 2.3.2 修改config/application.yml为:
|
||||||
|
```
|
||||||
|
server:
|
||||||
|
port: 8081
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.alibaba.otter.canal.client.adapter.hbase: DEBUG
|
||||||
|
spring:
|
||||||
|
jackson:
|
||||||
|
date-format: yyyy-MM-dd HH:mm:ss
|
||||||
|
time-zone: GMT+8
|
||||||
|
default-property-inclusion: non_null
|
||||||
|
|
||||||
|
canal.conf:
|
||||||
|
canalServerHost: 127.0.0.1:11111
|
||||||
|
flatMessage: true
|
||||||
|
canalInstances:
|
||||||
|
- instance: example
|
||||||
|
adapterGroups:
|
||||||
|
- outAdapters:
|
||||||
|
- name: logger
|
||||||
|
```
|
||||||
|
启动 canal-adapter-launcher.jar
|
||||||
|
```
|
||||||
|
java -jar canal-adapter-launcher.jar
|
||||||
|
```
|
||||||
|
|
||||||
|
## 三、HBase适配器
|
||||||
|
### 3.1 修改启动器配置: application.yml
|
||||||
|
```
|
||||||
|
server:
|
||||||
|
port: 8081
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.alibaba.otter.canal.client.adapter.hbase: DEBUG
|
||||||
|
spring:
|
||||||
|
jackson:
|
||||||
|
date-format: yyyy-MM-dd HH:mm:ss
|
||||||
|
time-zone: GMT+8
|
||||||
|
default-property-inclusion: non_null
|
||||||
|
|
||||||
|
canal.conf:
|
||||||
|
canalServerHost: 127.0.0.1:11111
|
||||||
|
flatMessage: true
|
||||||
|
canalInstances:
|
||||||
|
- instance: example
|
||||||
|
adapterGroups:
|
||||||
|
- outAdapters:
|
||||||
|
- name: hbase
|
||||||
|
properties:
|
||||||
|
hbase.zookeeper.quorum: slave1
|
||||||
|
hbase.zookeeper.property.clientPort: 2181
|
||||||
|
zookeeper.znode.parent: /hbase
|
||||||
|
|
||||||
|
adapter.conf:
|
||||||
|
datasourceConfigs:
|
||||||
|
defaultDS:
|
||||||
|
url: jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true
|
||||||
|
username: root
|
||||||
|
password: 121212
|
||||||
|
adapterConfigs:
|
||||||
|
- hbase/mytest_person.yml
|
||||||
|
```
|
||||||
|
其中指定了一个HBase表映射文件: mytest_person.yml
|
||||||
|
### 3.2 适配器表映射文件
|
||||||
|
修改 config/hbase/mytest_person.yml文件:
|
||||||
|
```
|
||||||
|
dataSourceKey: defaultDS # 对应application.yml中的datasourceConfigs下的配置
|
||||||
|
hbaseMapping: # mysql--HBase的单表映射配置
|
||||||
|
mode: STRING # HBase中的存储类型, 默认统一存为String, 可选: #PHOENIX #NATIVE #STRING
|
||||||
|
# NATIVE: 以java类型为主, PHOENIX: 将类型转换为Phoenix对应的类型
|
||||||
|
destination: example # 对应 canal destination/MQ topic 名称
|
||||||
|
database: mytest # 数据库名/schema名
|
||||||
|
table: person # 表名
|
||||||
|
hbaseTable: MYTEST.PERSON # HBase表名
|
||||||
|
family: CF # 默认统一Column Family名称
|
||||||
|
uppercaseQualifier: true # 字段名转大写, 默认为true
|
||||||
|
commitBatch: 3000 # 批量提交的大小, ETL中用到
|
||||||
|
#rowKey: id,type # 复合字段rowKey不能和columns中的rowKey并存
|
||||||
|
# 复合rowKey会以 '|' 分隔
|
||||||
|
columns: # 字段映射, 如果不配置将自动映射所有字段,
|
||||||
|
# 并取第一个字段为rowKey, HBase字段名以mysql字段名为主
|
||||||
|
id: ROWKE
|
||||||
|
name: CF:NAME
|
||||||
|
email: EMAIL # 如果column family为默认CF, 则可以省略
|
||||||
|
type: # 如果HBase字段和mysql字段名一致, 则可以省略
|
||||||
|
c_time:
|
||||||
|
birthday:
|
||||||
|
```
|
||||||
|
如果涉及到类型转换,可以如下形式:
|
||||||
|
```
|
||||||
|
...
|
||||||
|
columns:
|
||||||
|
id: ROWKE$STRING
|
||||||
|
...
|
||||||
|
type: TYPE$BYTE
|
||||||
|
...
|
||||||
|
```
|
||||||
|
类型转换涉及到Java类型和Phoenix类型两种, 分别定义如下:
|
||||||
|
```
|
||||||
|
#Java 类型转换, 对应配置 mode: NATIVE
|
||||||
|
$DEFAULT
|
||||||
|
$STRING
|
||||||
|
$INTEGER
|
||||||
|
$LONG
|
||||||
|
$SHORT
|
||||||
|
$BOOLEAN
|
||||||
|
$FLOAT
|
||||||
|
$DOUBLE
|
||||||
|
$BIGDECIMAL
|
||||||
|
$DATE
|
||||||
|
$BYTE
|
||||||
|
$BYTES
|
||||||
|
```
|
||||||
|
```
|
||||||
|
#Phoenix 类型转换, 对应配置 mode: PHOENIX
|
||||||
|
$DEFAULT 对应PHOENIX里的VARCHAR
|
||||||
|
$UNSIGNED_INT 对应PHOENIX里的UNSIGNED_INT 4字节
|
||||||
|
$UNSIGNED_LONG 对应PHOENIX里的UNSIGNED_LONG 8字节
|
||||||
|
$UNSIGNED_TINYINT 对应PHOENIX里的UNSIGNED_TINYINT 1字节
|
||||||
|
$UNSIGNED_SMALLINT 对应PHOENIX里的UNSIGNED_SMALLINT 2字节
|
||||||
|
$UNSIGNED_FLOAT 对应PHOENIX里的UNSIGNED_FLOAT 4字节
|
||||||
|
$UNSIGNED_DOUBLE 对应PHOENIX里的UNSIGNED_DOUBLE 8字节
|
||||||
|
$INTEGER 对应PHOENIX里的INTEGER 4字节
|
||||||
|
$BIGINT 对应PHOENIX里的BIGINT 8字节
|
||||||
|
$TINYINT 对应PHOENIX里的TINYINT 1字节
|
||||||
|
$SMALLINT 对应PHOENIX里的SMALLINT 2字节
|
||||||
|
$FLOAT 对应PHOENIX里的FLOAT 4字节
|
||||||
|
$DOUBLE 对应PHOENIX里的DOUBLE 8字节
|
||||||
|
$BOOLEAN 对应PHOENIX里的BOOLEAN 1字节
|
||||||
|
$TIME 对应PHOENIX里的TIME 8字节
|
||||||
|
$DATE 对应PHOENIX里的DATE 8字节
|
||||||
|
$TIMESTAMP 对应PHOENIX里的TIMESTAMP 12字节
|
||||||
|
$UNSIGNED_TIME 对应PHOENIX里的UNSIGNED_TIME 8字节
|
||||||
|
$UNSIGNED_DATE 对应PHOENIX里的UNSIGNED_DATE 8字节
|
||||||
|
$UNSIGNED_TIMESTAMP 对应PHOENIX里的UNSIGNED_TIMESTAMP 12字节
|
||||||
|
$VARCHAR 对应PHOENIX里的VARCHAR 动态长度
|
||||||
|
$VARBINARY 对应PHOENIX里的VARBINARY 动态长度
|
||||||
|
$DECIMAL 对应PHOENIX里的DECIMAL 动态长度
|
||||||
|
```
|
||||||
|
如果不配置将以java对象原生类型默认映射转换
|
||||||
|
### 3.3 启动HBase数据同步
|
||||||
|
#### 创建HBase表
|
||||||
|
在HBase shell中运行:
|
||||||
|
```
|
||||||
|
create 'MYTEST.PERSON', {NAME=>'CF'}
|
||||||
|
```
|
||||||
|
#### 启动canal-adapter启动器
|
||||||
|
```
|
||||||
|
java -jar canal-adapter-launcher.jar
|
||||||
|
```
|
||||||
|
#### 验证
|
||||||
|
修改mysql mytest.person表的数据, 将会自动同步到HBase的MYTEST.PERSON表下面, 并会打出DML的log
|
||||||
@@ -1,11 +1,9 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
<version>1.1.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
@@ -16,18 +14,23 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<artifactId>canal.protocol</artifactId>
|
<artifactId>canal.protocol</artifactId>
|
||||||
<version>${project.version}</version>
|
<version>1.1.1</version>
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.slf4j</groupId>
|
|
||||||
<artifactId>slf4j-api</artifactId>
|
|
||||||
<version>1.7.12</version>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>joda-time</groupId>
|
<groupId>joda-time</groupId>
|
||||||
<artifactId>joda-time</artifactId>
|
<artifactId>joda-time</artifactId>
|
||||||
<version>2.9.4</version>
|
<version>2.9.4</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba</groupId>
|
||||||
|
<artifactId>druid</artifactId>
|
||||||
|
<version>1.1.9</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-java</artifactId>
|
||||||
|
<version>5.1.40</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -1,34 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.CanalOuterAdapterConfiguration;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 外部适配器接口
|
|
||||||
*
|
|
||||||
* @author machengyuan 2018-8-18 下午10:14:02
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
@SPI("logger")
|
|
||||||
public interface CanalOuterAdapter {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 外部适配器初始化接口
|
|
||||||
*
|
|
||||||
* @param configuration 外部适配器配置信息
|
|
||||||
*/
|
|
||||||
void init(CanalOuterAdapterConfiguration configuration);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 往适配器中写入数据
|
|
||||||
*
|
|
||||||
* @param message message数据包
|
|
||||||
*/
|
|
||||||
void writeOut(Message message);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 外部适配器销毁接口
|
|
||||||
*/
|
|
||||||
void destroy();
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外部适配器接口
|
||||||
|
*
|
||||||
|
* @author reweerma 2018-8-18 下午10:14:02
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@SPI("logger")
|
||||||
|
public interface OuterAdapter {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外部适配器初始化接口
|
||||||
|
*
|
||||||
|
* @param configuration 外部适配器配置信息
|
||||||
|
*/
|
||||||
|
void init(OuterAdapterConfig configuration);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 往适配器中同步数据
|
||||||
|
*
|
||||||
|
* @param dml 数据包
|
||||||
|
*/
|
||||||
|
void sync(Dml dml);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外部适配器销毁接口
|
||||||
|
*/
|
||||||
|
void destroy();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Etl操作
|
||||||
|
*
|
||||||
|
* @param task 任务名, 对应配置名
|
||||||
|
* @param params etl筛选条件
|
||||||
|
*/
|
||||||
|
default EtlResult etl(String task, List<String> params) {
|
||||||
|
throw new UnsupportedOperationException("unsupported operation");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算总数
|
||||||
|
*
|
||||||
|
* @param task 任务名, 对应配置名
|
||||||
|
* @return 总数
|
||||||
|
*/
|
||||||
|
default Map<String, Object> count(String task) {
|
||||||
|
throw new UnsupportedOperationException("unsupported operation");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通过task获取对应的destination
|
||||||
|
*
|
||||||
|
* @param task 任务名, 对应配置名
|
||||||
|
* @return destination
|
||||||
|
*/
|
||||||
|
default String getDestination(String task) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.support;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 适配器配置集合, 用于配置加载, 线程不安全
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class AdapterConfigs {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 类型下对应所有配置名, 如:
|
||||||
|
* hbase
|
||||||
|
* ┗━ mytest_person.yml
|
||||||
|
* ┗━ mytest_role.yml
|
||||||
|
* ┗━ mytest_department.yml
|
||||||
|
*/
|
||||||
|
private static Map<String, Set<String>> configs = new HashMap<>();
|
||||||
|
|
||||||
|
public static void put(String key, String value) {
|
||||||
|
Set<String> values = configs.get(key);
|
||||||
|
if (values == null) {
|
||||||
|
values = new LinkedHashSet<>();
|
||||||
|
}
|
||||||
|
values.add(value);
|
||||||
|
configs.put(key, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Set<String> get(String key) {
|
||||||
|
return configs.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void clear() {
|
||||||
|
configs.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,27 +2,26 @@ package com.alibaba.otter.canal.client.adapter.support;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 配置信息类
|
* 配置信息类
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-18 下午10:40:12
|
* @author rewerma 2018-8-18 下午10:40:12
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class CanalClientConfig {
|
public class CanalClientConfig {
|
||||||
|
|
||||||
private String canalServerHost;
|
private String canalServerHost; // 单机模式下canal server的 ip:port
|
||||||
|
|
||||||
private String zookeeperHosts;
|
private String zookeeperHosts; // 集群模式下的zk地址, 如果配置了单机地址则以单机为准!!
|
||||||
|
|
||||||
private Properties properties;
|
private String bootstrapServers; // kafka or rocket mq 地址
|
||||||
|
|
||||||
private String bootstrapServers;
|
private Boolean flatMessage = true; // 是否已flatMessage模式传输, 只适用于mq模式
|
||||||
|
|
||||||
private List<KafkaTopic> kafkaTopics;
|
private List<MQTopic> mqTopics; // mq topic 列表
|
||||||
|
|
||||||
private List<CanalInstance> canalInstances;
|
private List<CanalInstance> canalInstances; // tcp 模式下 canal 实例列表, 与mq模式不能共存!!
|
||||||
|
|
||||||
public String getCanalServerHost() {
|
public String getCanalServerHost() {
|
||||||
return canalServerHost;
|
return canalServerHost;
|
||||||
@@ -40,14 +39,6 @@ public class CanalClientConfig {
|
|||||||
this.zookeeperHosts = zookeeperHosts;
|
this.zookeeperHosts = zookeeperHosts;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Properties getProperties() {
|
|
||||||
return properties;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setProperties(Properties properties) {
|
|
||||||
this.properties = properties;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getBootstrapServers() {
|
public String getBootstrapServers() {
|
||||||
return bootstrapServers;
|
return bootstrapServers;
|
||||||
}
|
}
|
||||||
@@ -56,12 +47,20 @@ public class CanalClientConfig {
|
|||||||
this.bootstrapServers = bootstrapServers;
|
this.bootstrapServers = bootstrapServers;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<KafkaTopic> getKafkaTopics() {
|
public List<MQTopic> getMqTopics() {
|
||||||
return kafkaTopics;
|
return mqTopics;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setKafkaTopics(List<KafkaTopic> kafkaTopics) {
|
public void setMqTopics(List<MQTopic> mqTopics) {
|
||||||
this.kafkaTopics = kafkaTopics;
|
this.mqTopics = mqTopics;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean getFlatMessage() {
|
||||||
|
return flatMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFlatMessage(Boolean flatMessage) {
|
||||||
|
this.flatMessage = flatMessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<CanalInstance> getCanalInstances() {
|
public List<CanalInstance> getCanalInstances() {
|
||||||
@@ -74,9 +73,9 @@ public class CanalClientConfig {
|
|||||||
|
|
||||||
public static class CanalInstance {
|
public static class CanalInstance {
|
||||||
|
|
||||||
private String instance;
|
private String instance; // 实例名
|
||||||
|
|
||||||
private List<AdapterGroup> adapterGroups;
|
private List<Group> groups; // 适配器分组列表
|
||||||
|
|
||||||
public String getInstance() {
|
public String getInstance() {
|
||||||
return instance;
|
return instance;
|
||||||
@@ -88,33 +87,44 @@ public class CanalClientConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<AdapterGroup> getAdapterGroups() {
|
public List<Group> getGroups() {
|
||||||
return adapterGroups;
|
return groups;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAdapterGroups(List<AdapterGroup> adapterGroups) {
|
public void setGroups(List<Group> groups) {
|
||||||
this.adapterGroups = adapterGroups;
|
this.groups = groups;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class AdapterGroup {
|
}
|
||||||
|
|
||||||
private List<CanalOuterAdapterConfiguration> outAdapters;
|
public static class Group {
|
||||||
|
|
||||||
public List<CanalOuterAdapterConfiguration> getOutAdapters() {
|
private List<OuterAdapterConfig> outAdapters; // 适配器列表
|
||||||
|
|
||||||
|
public List<OuterAdapterConfig> getOutAdapters() {
|
||||||
return outAdapters;
|
return outAdapters;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setOutAdapters(List<CanalOuterAdapterConfiguration> outAdapters) {
|
public void setOutAdapters(List<OuterAdapterConfig> outAdapters) {
|
||||||
this.outAdapters = outAdapters;
|
this.outAdapters = outAdapters;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class KafkaTopic {
|
public static class MQTopic {
|
||||||
|
|
||||||
private String topic;
|
private String mqMode; // mq模式 kafka or rocketMQ
|
||||||
|
|
||||||
private List<Group> groups = new ArrayList<>();
|
private String topic; // topic名
|
||||||
|
|
||||||
|
private List<MQGroup> groups = new ArrayList<>(); // 分组列表
|
||||||
|
|
||||||
|
public String getMqMode() {
|
||||||
|
return mqMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMqMode(String mqMode) {
|
||||||
|
this.mqMode = mqMode;
|
||||||
|
}
|
||||||
|
|
||||||
public String getTopic() {
|
public String getTopic() {
|
||||||
return topic;
|
return topic;
|
||||||
@@ -124,22 +134,20 @@ public class CanalClientConfig {
|
|||||||
this.topic = topic;
|
this.topic = topic;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Group> getGroups() {
|
public List<MQGroup> getGroups() {
|
||||||
return groups;
|
return groups;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setGroups(List<Group> groups) {
|
public void setGroups(List<MQGroup> groups) {
|
||||||
this.groups = groups;
|
this.groups = groups;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Group {
|
public static class MQGroup {
|
||||||
|
|
||||||
private String groupId;
|
private String groupId; // group id
|
||||||
|
|
||||||
// private List<Adaptor> adapters = new ArrayList<>();
|
private List<OuterAdapterConfig> outAdapters; // 适配器配置列表
|
||||||
|
|
||||||
private List<CanalOuterAdapterConfiguration> outAdapters;
|
|
||||||
|
|
||||||
public String getGroupId() {
|
public String getGroupId() {
|
||||||
return groupId;
|
return groupId;
|
||||||
@@ -149,33 +157,14 @@ public class CanalClientConfig {
|
|||||||
this.groupId = groupId;
|
this.groupId = groupId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<CanalOuterAdapterConfiguration> getOutAdapters() {
|
public List<OuterAdapterConfig> getOutAdapters() {
|
||||||
return outAdapters;
|
return outAdapters;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setOutAdapters(List<CanalOuterAdapterConfiguration> outAdapters) {
|
public void setOutAdapters(List<OuterAdapterConfig> outAdapters) {
|
||||||
this.outAdapters = outAdapters;
|
this.outAdapters = outAdapters;
|
||||||
}
|
}
|
||||||
|
|
||||||
// public List<Adaptor> getAdapters() {
|
|
||||||
// return adapters;
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// public void setAdapters(List<Adaptor> adapters) {
|
|
||||||
// this.adapters = adapters;
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// public static class Adaptor {
|
|
||||||
// private List<CanalOuterAdapterConfiguration> outAdapters;
|
|
||||||
//
|
|
||||||
// public List<CanalOuterAdapterConfiguration> getOutAdapters() {
|
|
||||||
// return outAdapters;
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// public void setOutAdapters(List<CanalOuterAdapterConfiguration> outAdapters)
|
|
||||||
// {
|
|
||||||
// this.outAdapters = outAdapters;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,52 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.support;
|
|
||||||
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 外部适配器配置信息类
|
|
||||||
*
|
|
||||||
* @author machengyuan 2018-8-18 下午10:15:12
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
public class CanalOuterAdapterConfiguration {
|
|
||||||
|
|
||||||
private String name; // 适配器名称, 如: logger, hbase, es
|
|
||||||
|
|
||||||
private String hosts; // 适配器内部的地址, 比如对应es该参数可以填写es的server地址
|
|
||||||
|
|
||||||
private String zkHosts; // 适配器内部的ZK地址, 比如对应HBase该参数可以填写HBase对应的ZK地址
|
|
||||||
|
|
||||||
private Properties properties; // 其余参数, 可填写适配器中的所需的配置信息
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getHosts() {
|
|
||||||
return hosts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setHosts(String hosts) {
|
|
||||||
this.hosts = hosts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Properties getProperties() {
|
|
||||||
return properties;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setProperties(Properties properties) {
|
|
||||||
this.properties = properties;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getZkHosts() {
|
|
||||||
return zkHosts;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setZkHosts(String zkHosts) {
|
|
||||||
this.zkHosts = zkHosts;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.support;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
import com.alibaba.druid.pool.DruidDataSource;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据源配置
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class DatasourceConfig {
|
||||||
|
|
||||||
|
public final static Map<String, DruidDataSource> DATA_SOURCES = new ConcurrentHashMap<>(); // key对应的数据源
|
||||||
|
|
||||||
|
private String driver = "com.mysql.jdbc.Driver"; // 默认为mysql jdbc驱动
|
||||||
|
private String url; // jdbc url
|
||||||
|
private String database; // jdbc database
|
||||||
|
private String type = "mysql"; // 类型, 默认为mysql
|
||||||
|
private String username; // jdbc username
|
||||||
|
private String password; // jdbc password
|
||||||
|
private Integer maxActive = 3; // 连接池最大连接数,默认为3
|
||||||
|
|
||||||
|
public String getDriver() {
|
||||||
|
return driver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDriver(String driver) {
|
||||||
|
this.driver = driver;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUrl() {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUrl(String url) {
|
||||||
|
this.url = url;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDatabase() {
|
||||||
|
return database;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDatabase(String database) {
|
||||||
|
this.database = database;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setType(String type) {
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPassword() {
|
||||||
|
return password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPassword(String password) {
|
||||||
|
this.password = password;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getMaxActive() {
|
||||||
|
return maxActive;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMaxActive(Integer maxActive) {
|
||||||
|
this.maxActive = maxActive;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,20 +7,32 @@ import java.util.Map;
|
|||||||
/**
|
/**
|
||||||
* DML操作转换对象
|
* DML操作转换对象
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-19 下午11:30:49
|
* @author rewerma 2018-8-19 下午11:30:49
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class Dml implements Serializable {
|
public class Dml implements Serializable {
|
||||||
|
|
||||||
private static final long serialVersionUID = 2611556444074013268L;
|
private static final long serialVersionUID = 2611556444074013268L;
|
||||||
|
|
||||||
private String database;
|
private String destination; // 对应canal的实例或者MQ的topic
|
||||||
private String table;
|
private String database; // 数据库或schema
|
||||||
private String type;
|
private String table; // 表名
|
||||||
private Long ts;
|
private String type; // 类型: INSERT UPDATE DELETE
|
||||||
private String sql;
|
// binlog executeTime
|
||||||
private List<Map<String, Object>> data;
|
private Long es; // 执行耗时
|
||||||
private List<Map<String, Object>> old;
|
// dml build timeStamp
|
||||||
|
private Long ts; // 同步时间
|
||||||
|
private String sql; // 执行的sql, dml sql为空
|
||||||
|
private List<Map<String, Object>> data; // 数据列表
|
||||||
|
private List<Map<String, Object>> old; // 旧数据列表, 用于update, size和data的size一一对应
|
||||||
|
|
||||||
|
public String getDestination() {
|
||||||
|
return destination;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDestination(String destination) {
|
||||||
|
this.destination = destination;
|
||||||
|
}
|
||||||
|
|
||||||
public String getDatabase() {
|
public String getDatabase() {
|
||||||
return database;
|
return database;
|
||||||
@@ -78,11 +90,20 @@ public class Dml implements Serializable {
|
|||||||
this.old = old;
|
this.old = old;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Long getEs() {
|
||||||
|
return es;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEs(Long es) {
|
||||||
|
this.es = es;
|
||||||
|
}
|
||||||
|
|
||||||
public void clear() {
|
public void clear() {
|
||||||
database = null;
|
database = null;
|
||||||
table = null;
|
table = null;
|
||||||
type = null;
|
type = null;
|
||||||
ts = null;
|
ts = null;
|
||||||
|
es = null;
|
||||||
data = null;
|
data = null;
|
||||||
old = null;
|
old = null;
|
||||||
sql = null;
|
sql = null;
|
||||||
@@ -90,7 +111,8 @@ public class Dml implements Serializable {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "Dml{" + "database='" + database + '\'' + ", table='" + table + '\'' + ", type='" + type + '\'' + ", ts="
|
return "Dml{" + "destination='" + destination + '\'' + ", database='" + database + '\'' + ", table='" + table
|
||||||
+ ts + ", sql='" + sql + '\'' + ", data=" + data + ", old=" + old + '}';
|
+ '\'' + ", type='" + type + '\'' + ", es=" + es + ", ts=" + ts + ", sql='" + sql + '\'' + ", data="
|
||||||
|
+ data + ", old=" + old + '}';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.support;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ETL的结果对象
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class EtlResult implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 4250522736289866505L;
|
||||||
|
|
||||||
|
private boolean succeeded = false;
|
||||||
|
|
||||||
|
private String resultMessage;
|
||||||
|
|
||||||
|
private String errorMessage;
|
||||||
|
|
||||||
|
public boolean getSucceeded() {
|
||||||
|
return succeeded;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSucceeded(boolean succeeded) {
|
||||||
|
this.succeeded = succeeded;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getResultMessage() {
|
||||||
|
return resultMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setResultMessage(String resultMessage) {
|
||||||
|
this.resultMessage = resultMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getErrorMessage() {
|
||||||
|
return errorMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setErrorMessage(String errorMessage) {
|
||||||
|
this.errorMessage = errorMessage;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
/**
|
/**
|
||||||
* SPI 类加载器
|
* SPI 类加载器
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-19 下午11:30:49
|
* @author rewerma 2018-8-19 下午11:30:49
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class ExtensionLoader<T> {
|
public class ExtensionLoader<T> {
|
||||||
@@ -296,10 +296,17 @@ public class ExtensionLoader<T> {
|
|||||||
throw new IllegalStateException("failed to get class loader resource");
|
throw new IllegalStateException("failed to get class loader resource");
|
||||||
}
|
}
|
||||||
String dirtyPath = url.toString();
|
String dirtyPath = url.toString();
|
||||||
String jarPath = dirtyPath.replaceAll("^.*file:/", ""); // removes file:/ and everything before it
|
String jarPath = dirtyPath.replaceAll("^.*file:/", ""); // removes
|
||||||
jarPath = jarPath.replaceAll("jar!.*", "jar"); // removes everything after .jar, if .jar exists in dirtyPath
|
// file:/ and
|
||||||
jarPath = jarPath.replaceAll("%20", " "); // necessary if path has spaces within
|
// everything
|
||||||
if (!jarPath.endsWith(".jar")) { // this is needed if you plan to run the app using Spring Tools Suit play
|
// before it
|
||||||
|
jarPath = jarPath.replaceAll("jar!.*", "jar"); // removes everything
|
||||||
|
// after .jar, if .jar
|
||||||
|
// exists in dirtyPath
|
||||||
|
jarPath = jarPath.replaceAll("%20", " "); // necessary if path has
|
||||||
|
// spaces within
|
||||||
|
if (!jarPath.endsWith(".jar")) { // this is needed if you plan to run
|
||||||
|
// the app using Spring Tools Suit play
|
||||||
// button.
|
// button.
|
||||||
jarPath = jarPath.replaceAll("/classes/.*", "/classes/");
|
jarPath = jarPath.replaceAll("/classes/.*", "/classes/");
|
||||||
}
|
}
|
||||||
@@ -363,7 +370,8 @@ public class ExtensionLoader<T> {
|
|||||||
if (name.startsWith("java.") || name.startsWith("org.slf4j.")
|
if (name.startsWith("java.") || name.startsWith("org.slf4j.")
|
||||||
|| name.startsWith("org.apache.logging")
|
|| name.startsWith("org.apache.logging")
|
||||||
|| name.startsWith("org.apache.commons.logging.")) {
|
|| name.startsWith("org.apache.commons.logging.")) {
|
||||||
// || name.startsWith("org.apache.hadoop.")) {
|
// || name.startsWith("org.apache.hadoop."))
|
||||||
|
// {
|
||||||
c = super.loadClass(name);
|
c = super.loadClass(name);
|
||||||
}
|
}
|
||||||
if (c != null) return c;
|
if (c != null) return c;
|
||||||
@@ -386,7 +394,8 @@ public class ExtensionLoader<T> {
|
|||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
|
Enumeration<URL>[] tmp = (Enumeration<URL>[]) new Enumeration<?>[2];
|
||||||
|
|
||||||
tmp[0] = findResources(name); // local class path first
|
tmp[0] = findResources(name); // local class
|
||||||
|
// path first
|
||||||
// tmp[1] = super.getResources(name);
|
// tmp[1] = super.getResources(name);
|
||||||
|
|
||||||
return new CompoundEnumeration<>(tmp);
|
return new CompoundEnumeration<>(tmp);
|
||||||
@@ -474,7 +483,9 @@ public class ExtensionLoader<T> {
|
|||||||
}
|
}
|
||||||
if (line.length() > 0) {
|
if (line.length() > 0) {
|
||||||
Class<?> clazz = classLoader.loadClass(line);
|
Class<?> clazz = classLoader.loadClass(line);
|
||||||
// Class<?> clazz = Class.forName(line, true, classLoader);
|
// Class<?> clazz =
|
||||||
|
// Class.forName(line, true,
|
||||||
|
// classLoader);
|
||||||
if (!type.isAssignableFrom(clazz)) {
|
if (!type.isAssignableFrom(clazz)) {
|
||||||
throw new IllegalStateException(
|
throw new IllegalStateException(
|
||||||
"Error when load extension class(interface: " + type
|
"Error when load extension class(interface: " + type
|
||||||
|
|||||||
@@ -2,10 +2,7 @@ package com.alibaba.otter.canal.client.adapter.support;
|
|||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import java.sql.Date;
|
import java.sql.*;
|
||||||
import java.sql.Time;
|
|
||||||
import java.sql.Timestamp;
|
|
||||||
import java.sql.Types;
|
|
||||||
|
|
||||||
import org.joda.time.DateTime;
|
import org.joda.time.DateTime;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -14,14 +11,63 @@ import org.slf4j.LoggerFactory;
|
|||||||
/**
|
/**
|
||||||
* 类型转换工具类
|
* 类型转换工具类
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-19 下午06:14:23
|
* @author rewerma 2018-8-19 下午06:14:23
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class JdbcTypeUtil {
|
public class JdbcTypeUtil {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(JdbcTypeUtil.class);
|
private static Logger logger = LoggerFactory.getLogger(JdbcTypeUtil.class);
|
||||||
|
|
||||||
public static Object typeConvert(String tableName, String columnName, String value, int sqlType, String mysqlType) {
|
public static Object getRSData(ResultSet rs, String columnName, int jdbcType) throws SQLException {
|
||||||
|
if (jdbcType == Types.BIT || jdbcType == Types.BOOLEAN) {
|
||||||
|
return rs.getByte(columnName);
|
||||||
|
} else {
|
||||||
|
return rs.getObject(columnName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Class<?> jdbcType2javaType(int jdbcType) {
|
||||||
|
switch (jdbcType) {
|
||||||
|
case Types.BIT:
|
||||||
|
case Types.BOOLEAN:
|
||||||
|
// return Boolean.class;
|
||||||
|
case Types.TINYINT:
|
||||||
|
return Byte.TYPE;
|
||||||
|
case Types.SMALLINT:
|
||||||
|
return Short.class;
|
||||||
|
case Types.INTEGER:
|
||||||
|
return Integer.class;
|
||||||
|
case Types.BIGINT:
|
||||||
|
return Long.class;
|
||||||
|
case Types.DECIMAL:
|
||||||
|
case Types.NUMERIC:
|
||||||
|
return BigDecimal.class;
|
||||||
|
case Types.REAL:
|
||||||
|
return Float.class;
|
||||||
|
case Types.FLOAT:
|
||||||
|
case Types.DOUBLE:
|
||||||
|
return Double.class;
|
||||||
|
case Types.CHAR:
|
||||||
|
case Types.VARCHAR:
|
||||||
|
case Types.LONGVARCHAR:
|
||||||
|
return String.class;
|
||||||
|
case Types.BINARY:
|
||||||
|
case Types.VARBINARY:
|
||||||
|
case Types.LONGVARBINARY:
|
||||||
|
case Types.BLOB:
|
||||||
|
return byte[].class;
|
||||||
|
case Types.DATE:
|
||||||
|
return java.sql.Date.class;
|
||||||
|
case Types.TIME:
|
||||||
|
return Time.class;
|
||||||
|
case Types.TIMESTAMP:
|
||||||
|
return Timestamp.class;
|
||||||
|
default:
|
||||||
|
return String.class;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object typeConvert(String columnName, String value, int sqlType, String mysqlType) {
|
||||||
if (value == null || value.equals("")) {
|
if (value == null || value.equals("")) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -96,7 +142,7 @@ public class JdbcTypeUtil {
|
|||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("table: {} column: {}, failed convert type {} to {}", tableName, columnName, value, sqlType);
|
logger.error("table: {} column: {}, failed convert type {} to {}", columnName, value, sqlType);
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,25 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.support;
|
package com.alibaba.otter.canal.client.adapter.support;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.protocol.CanalEntry;
|
import com.alibaba.otter.canal.protocol.CanalEntry;
|
||||||
|
import com.alibaba.otter.canal.protocol.FlatMessage;
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message对象解析工具类
|
* Message对象解析工具类
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-19 下午06:14:23
|
* @author rewerma 2018-8-19 下午06:14:23
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class MessageUtil {
|
public class MessageUtil {
|
||||||
|
|
||||||
public static void parse4Dml(Message message, Consumer<Dml> consumer) {
|
public static void parse4Dml(String destination, Message message, Consumer<Dml> consumer) {
|
||||||
if (message == null) {
|
if (message == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -36,9 +42,11 @@ public class MessageUtil {
|
|||||||
CanalEntry.EventType eventType = rowChange.getEventType();
|
CanalEntry.EventType eventType = rowChange.getEventType();
|
||||||
|
|
||||||
final Dml dml = new Dml();
|
final Dml dml = new Dml();
|
||||||
|
dml.setDestination(destination);
|
||||||
dml.setDatabase(entry.getHeader().getSchemaName());
|
dml.setDatabase(entry.getHeader().getSchemaName());
|
||||||
dml.setTable(entry.getHeader().getTableName());
|
dml.setTable(entry.getHeader().getTableName());
|
||||||
dml.setType(eventType.toString());
|
dml.setType(eventType.toString());
|
||||||
|
dml.setEs(entry.getHeader().getExecuteTime());
|
||||||
dml.setTs(System.currentTimeMillis());
|
dml.setTs(System.currentTimeMillis());
|
||||||
dml.setSql(rowChange.getSql());
|
dml.setSql(rowChange.getSql());
|
||||||
List<Map<String, Object>> data = new ArrayList<>();
|
List<Map<String, Object>> data = new ArrayList<>();
|
||||||
@@ -63,8 +71,7 @@ public class MessageUtil {
|
|||||||
|
|
||||||
for (CanalEntry.Column column : columns) {
|
for (CanalEntry.Column column : columns) {
|
||||||
row.put(column.getName(),
|
row.put(column.getName(),
|
||||||
JdbcTypeUtil.typeConvert(dml.getTable(),
|
JdbcTypeUtil.typeConvert(column.getName(),
|
||||||
column.getName(),
|
|
||||||
column.getValue(),
|
column.getValue(),
|
||||||
column.getSqlType(),
|
column.getSqlType(),
|
||||||
column.getMysqlType()));
|
column.getMysqlType()));
|
||||||
@@ -82,8 +89,7 @@ public class MessageUtil {
|
|||||||
for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
|
for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
|
||||||
if (updateSet.contains(column.getName())) {
|
if (updateSet.contains(column.getName())) {
|
||||||
rowOld.put(column.getName(),
|
rowOld.put(column.getName(),
|
||||||
JdbcTypeUtil.typeConvert(dml.getTable(),
|
JdbcTypeUtil.typeConvert(column.getName(),
|
||||||
column.getName(),
|
|
||||||
column.getValue(),
|
column.getValue(),
|
||||||
column.getSqlType(),
|
column.getSqlType(),
|
||||||
column.getMysqlType()));
|
column.getMysqlType()));
|
||||||
@@ -101,9 +107,63 @@ public class MessageUtil {
|
|||||||
if (!old.isEmpty()) {
|
if (!old.isEmpty()) {
|
||||||
dml.setOld(old);
|
dml.setOld(old);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
consumer.accept(dml);
|
consumer.accept(dml);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static Dml flatMessage2Dml(String destination, FlatMessage flatMessage) {
|
||||||
|
if (flatMessage == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
Dml dml = new Dml();
|
||||||
|
dml.setDestination(destination);
|
||||||
|
dml.setDatabase(flatMessage.getDatabase());
|
||||||
|
dml.setTable(flatMessage.getTable());
|
||||||
|
dml.setType(flatMessage.getType());
|
||||||
|
dml.setTs(flatMessage.getTs());
|
||||||
|
dml.setEs(flatMessage.getEs());
|
||||||
|
dml.setSql(flatMessage.getSql());
|
||||||
|
if (flatMessage.getSqlType() == null || flatMessage.getMysqlType() == null) {
|
||||||
|
throw new RuntimeException("SqlType or mysqlType is null");
|
||||||
|
}
|
||||||
|
List<Map<String, String>> data = flatMessage.getData();
|
||||||
|
if (data != null) {
|
||||||
|
dml.setData(changeRows(data, flatMessage.getSqlType(), flatMessage.getMysqlType()));
|
||||||
|
}
|
||||||
|
List<Map<String, String>> old = flatMessage.getOld();
|
||||||
|
if (old != null) {
|
||||||
|
dml.setOld(changeRows(old, flatMessage.getSqlType(), flatMessage.getMysqlType()));
|
||||||
|
}
|
||||||
|
return dml;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Map<String, Object>> changeRows(List<Map<String, String>> rows, Map<String, Integer> sqlTypes,
|
||||||
|
Map<String, String> mysqlTypes) {
|
||||||
|
List<Map<String, Object>> result = new ArrayList<>();
|
||||||
|
for (Map<String, String> row : rows) {
|
||||||
|
Map<String, Object> resultRow = new LinkedHashMap<>();
|
||||||
|
for (Map.Entry<String, String> entry : row.entrySet()) {
|
||||||
|
String columnName = entry.getKey();
|
||||||
|
String columnValue = entry.getValue();
|
||||||
|
|
||||||
|
Integer sqlType = sqlTypes.get(columnName);
|
||||||
|
if (sqlType == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
String mysqlType = mysqlTypes.get(columnName);
|
||||||
|
if (mysqlType == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object finalValue = JdbcTypeUtil.typeConvert(columnName, columnValue, sqlType, mysqlType);
|
||||||
|
resultRow.put(columnName, finalValue);
|
||||||
|
}
|
||||||
|
result.add(resultRow);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public interface Consumer<T> {
|
public interface Consumer<T> {
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.support;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外部适配器配置信息类
|
||||||
|
*
|
||||||
|
* @author rewerma 2018-8-18 下午10:15:12
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class OuterAdapterConfig {
|
||||||
|
|
||||||
|
private String name; // 适配器名称, 如: logger, hbase, es
|
||||||
|
|
||||||
|
private String hosts; // 适配器内部的地址, 比如对应es该参数可以填写es的server地址
|
||||||
|
|
||||||
|
private String zkHosts; // 适配器内部的ZK地址, 比如对应HBase该参数可以填写HBase对应的ZK地址
|
||||||
|
|
||||||
|
private Map<String, String> properties; // 其余参数, 可填写适配器中的所需的配置信息
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHosts() {
|
||||||
|
return hosts;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setHosts(String hosts) {
|
||||||
|
this.hosts = hosts;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, String> getProperties() {
|
||||||
|
return properties;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setProperties(Map<String, String> properties) {
|
||||||
|
this.properties = properties;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getZkHosts() {
|
||||||
|
return zkHosts;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setZkHosts(String zkHosts) {
|
||||||
|
this.zkHosts = zkHosts;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.support;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用于rest的结果返回对象
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class Result implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = -3276409502352405716L;
|
||||||
|
public Integer code = 20000;
|
||||||
|
public Object data;
|
||||||
|
public String message;
|
||||||
|
public Date sysTime;
|
||||||
|
|
||||||
|
public static Result createSuccess(String message) {
|
||||||
|
Result result = new Result();
|
||||||
|
result.setMessage(message);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getCode() {
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCode(Integer code) {
|
||||||
|
this.code = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object getData() {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setData(Object data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMessage(String message) {
|
||||||
|
this.message = message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getSysTime() {
|
||||||
|
return sysTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSysTime(Date sysTime) {
|
||||||
|
this.sysTime = sysTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,17 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.support;
|
package com.alibaba.otter.canal.client.adapter.support;
|
||||||
|
|
||||||
import java.lang.annotation.*;
|
import java.lang.annotation.Documented;
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SPI装载器注解
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
@Documented
|
@Documented
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
@Target({ ElementType.TYPE })
|
@Target({ ElementType.TYPE })
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
<version>1.1.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
@@ -22,7 +20,8 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.yaml</groupId>
|
<groupId>org.yaml</groupId>
|
||||||
<artifactId>snakeyaml</artifactId>
|
<artifactId>snakeyaml</artifactId>
|
||||||
<version>1.17</version>
|
<version>1.19</version>
|
||||||
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.hbase</groupId>
|
<groupId>org.apache.hbase</groupId>
|
||||||
@@ -44,38 +43,6 @@
|
|||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-jar-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<archive>
|
|
||||||
<addMavenDescriptor>true</addMavenDescriptor>
|
|
||||||
</archive>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/hbase-mapping/**</exclude>
|
|
||||||
</excludes>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-antrun-plugin</artifactId>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<phase>package</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>run</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<tasks>
|
|
||||||
<copy todir="${project.basedir}/../../client-launcher/target/canal_client/conf/hbase-mapping" overwrite="true" >
|
|
||||||
<fileset dir="${project.basedir}/src/main/resources/hbase-mapping" erroronmissingdir="true">
|
|
||||||
<include name="*.conf"/>
|
|
||||||
<include name="*.yml"/>
|
|
||||||
</fileset>
|
|
||||||
</copy>
|
|
||||||
</tasks>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
|
|||||||
@@ -2,23 +2,29 @@ package com.alibaba.otter.canal.client.adapter.hbase;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
import org.apache.commons.lang.StringUtils;
|
||||||
import org.apache.hadoop.conf.Configuration;
|
import org.apache.hadoop.conf.Configuration;
|
||||||
import org.apache.hadoop.hbase.HBaseConfiguration;
|
import org.apache.hadoop.hbase.HBaseConfiguration;
|
||||||
import org.apache.hadoop.hbase.client.Connection;
|
import org.apache.hadoop.hbase.TableName;
|
||||||
import org.apache.hadoop.hbase.client.ConnectionFactory;
|
import org.apache.hadoop.hbase.client.*;
|
||||||
|
import org.apache.hadoop.hbase.client.Result;
|
||||||
|
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.CanalOuterAdapter;
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfig;
|
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfigLoader;
|
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfigLoader;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseEtlService;
|
||||||
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseSyncService;
|
import com.alibaba.otter.canal.client.adapter.hbase.service.HbaseSyncService;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.CanalOuterAdapterConfiguration;
|
import com.alibaba.otter.canal.client.adapter.hbase.support.HbaseTemplate;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
import com.alibaba.otter.canal.client.adapter.support.*;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.MessageUtil;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HBase外部适配器
|
* HBase外部适配器
|
||||||
@@ -27,79 +33,126 @@ import com.alibaba.otter.canal.protocol.Message;
|
|||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
@SPI("hbase")
|
@SPI("hbase")
|
||||||
public class HbaseAdapter implements CanalOuterAdapter {
|
public class HbaseAdapter implements OuterAdapter {
|
||||||
|
|
||||||
private static volatile Map<String, MappingConfig> mappingConfigCache = null;
|
private static Logger logger = LoggerFactory.getLogger(HbaseAdapter.class);
|
||||||
|
|
||||||
|
private static volatile Map<String, MappingConfig> hbaseMapping = null; // 文件名对应配置
|
||||||
|
private static volatile Map<String, MappingConfig> mappingConfigCache = null; // 库名-表名对应配置
|
||||||
|
|
||||||
private Connection conn;
|
private Connection conn;
|
||||||
private HbaseSyncService hbaseSyncService;
|
private HbaseSyncService hbaseSyncService;
|
||||||
|
private HbaseTemplate hbaseTemplate;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void init(CanalOuterAdapterConfiguration configuration) {
|
public void init(OuterAdapterConfig configuration) {
|
||||||
try {
|
try {
|
||||||
if (mappingConfigCache == null) {
|
if (mappingConfigCache == null) {
|
||||||
synchronized (MappingConfig.class) {
|
synchronized (MappingConfig.class) {
|
||||||
if (mappingConfigCache == null) {
|
if (mappingConfigCache == null) {
|
||||||
Map<String, MappingConfig> hbaseMapping = MappingConfigLoader.load();
|
hbaseMapping = MappingConfigLoader.load();
|
||||||
mappingConfigCache = new HashMap<>();
|
mappingConfigCache = new HashMap<>();
|
||||||
for (MappingConfig mappingConfig : hbaseMapping.values()) {
|
for (MappingConfig mappingConfig : hbaseMapping.values()) {
|
||||||
mappingConfigCache.put(mappingConfig.getHbaseOrm().getDatabase() + "-"
|
mappingConfigCache.put(StringUtils.trimToEmpty(mappingConfig.getHbaseMapping().getDestination())
|
||||||
+ mappingConfig.getHbaseOrm().getTable(),
|
+ "." + mappingConfig.getHbaseMapping().getDatabase() + "."
|
||||||
|
+ mappingConfig.getHbaseMapping().getTable(),
|
||||||
mappingConfig);
|
mappingConfig);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String hosts = configuration.getZkHosts();
|
Map<String, String> propertites = configuration.getProperties();
|
||||||
if (StringUtils.isEmpty(hosts)) {
|
|
||||||
hosts = configuration.getHosts();
|
|
||||||
}
|
|
||||||
if (StringUtils.isEmpty(hosts)) {
|
|
||||||
throw new RuntimeException("Empty zookeeper hosts");
|
|
||||||
}
|
|
||||||
String[] zkHosts = StringUtils.split(hosts, ",");
|
|
||||||
int zkPort = 0;
|
|
||||||
StringBuilder hostsWithoutPort = new StringBuilder();
|
|
||||||
for (String host : zkHosts) {
|
|
||||||
int i = host.indexOf(":");
|
|
||||||
hostsWithoutPort.append(host, 0, i);
|
|
||||||
hostsWithoutPort.append(",");
|
|
||||||
if (zkPort == 0) zkPort = Integer.parseInt(host.substring(i + 1));
|
|
||||||
}
|
|
||||||
hostsWithoutPort.deleteCharAt(hostsWithoutPort.length() - 1);
|
|
||||||
|
|
||||||
String znode = configuration.getProperties().getProperty("znodeParent");
|
|
||||||
if (StringUtils.isEmpty(znode)) {
|
|
||||||
znode = "/hbase";
|
|
||||||
}
|
|
||||||
|
|
||||||
Configuration hbaseConfig = HBaseConfiguration.create();
|
Configuration hbaseConfig = HBaseConfiguration.create();
|
||||||
hbaseConfig.set("hbase.zookeeper.quorum", hostsWithoutPort.toString());
|
propertites.forEach(hbaseConfig::set);
|
||||||
hbaseConfig.set("hbase.zookeeper.property.clientPort", Integer.toString(zkPort));
|
|
||||||
hbaseConfig.set("zookeeper.znode.parent", znode);
|
|
||||||
conn = ConnectionFactory.createConnection(hbaseConfig);
|
conn = ConnectionFactory.createConnection(hbaseConfig);
|
||||||
hbaseSyncService = new HbaseSyncService(conn);
|
hbaseTemplate = new HbaseTemplate(conn);
|
||||||
|
hbaseSyncService = new HbaseSyncService(hbaseTemplate);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void writeOut(Message message) {
|
public void sync(Dml dml) {
|
||||||
MessageUtil.parse4Dml(message, new MessageUtil.Consumer<Dml>() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void accept(Dml dml) {
|
|
||||||
if (dml == null) {
|
if (dml == null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
String destination = StringUtils.trimToEmpty(dml.getDestination());
|
||||||
String database = dml.getDatabase();
|
String database = dml.getDatabase();
|
||||||
String table = dml.getTable();
|
String table = dml.getTable();
|
||||||
MappingConfig config = mappingConfigCache.get(database + "-" + table);
|
MappingConfig config = mappingConfigCache.get(destination + "." + database + "." + table);
|
||||||
hbaseSyncService.sync(config, dml);
|
hbaseSyncService.sync(config, dml);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
@Override
|
||||||
|
public EtlResult etl(String task, List<String> params) {
|
||||||
|
EtlResult etlResult = new EtlResult();
|
||||||
|
MappingConfig config = hbaseMapping.get(task);
|
||||||
|
if (config != null) {
|
||||||
|
DataSource dataSource = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey());
|
||||||
|
if (dataSource != null) {
|
||||||
|
return HbaseEtlService.importData(dataSource, hbaseTemplate, config, params);
|
||||||
|
} else {
|
||||||
|
etlResult.setSucceeded(false);
|
||||||
|
etlResult.setErrorMessage("DataSource not found");
|
||||||
|
return etlResult;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
DataSource dataSource = DatasourceConfig.DATA_SOURCES.get(task);
|
||||||
|
if (dataSource != null) {
|
||||||
|
StringBuilder resultMsg = new StringBuilder();
|
||||||
|
boolean resSucc = true;
|
||||||
|
// ds不为空说明传入的是datasourceKey
|
||||||
|
for (MappingConfig configTmp : hbaseMapping.values()) {
|
||||||
|
// 取所有的datasourceKey为task的配置
|
||||||
|
if (configTmp.getDataSourceKey().equals(task)) {
|
||||||
|
EtlResult etlRes = HbaseEtlService.importData(dataSource, hbaseTemplate, configTmp, params);
|
||||||
|
if (!etlRes.getSucceeded()) {
|
||||||
|
resSucc = false;
|
||||||
|
resultMsg.append(etlRes.getErrorMessage()).append("\n");
|
||||||
|
} else {
|
||||||
|
resultMsg.append(etlRes.getResultMessage()).append("\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (resultMsg.length() > 0) {
|
||||||
|
etlResult.setSucceeded(resSucc);
|
||||||
|
if (resSucc) {
|
||||||
|
etlResult.setResultMessage(resultMsg.toString());
|
||||||
|
} else {
|
||||||
|
etlResult.setErrorMessage(resultMsg.toString());
|
||||||
|
}
|
||||||
|
return etlResult;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
etlResult.setSucceeded(false);
|
||||||
|
etlResult.setErrorMessage("Task not found");
|
||||||
|
return etlResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> count(String task) {
|
||||||
|
MappingConfig config = hbaseMapping.get(task);
|
||||||
|
String hbaseTable = config.getHbaseMapping().getHbaseTable();
|
||||||
|
long rowCount = 0L;
|
||||||
|
try {
|
||||||
|
HTable table = (HTable) conn.getTable(TableName.valueOf(hbaseTable));
|
||||||
|
Scan scan = new Scan();
|
||||||
|
scan.setFilter(new FirstKeyOnlyFilter());
|
||||||
|
ResultScanner resultScanner = table.getScanner(scan);
|
||||||
|
for (Result result : resultScanner) {
|
||||||
|
rowCount += result.size();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
Map<String, Object> res = new LinkedHashMap<>();
|
||||||
|
res.put("hbaseTable", hbaseTable);
|
||||||
|
res.put("count", rowCount);
|
||||||
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -112,4 +165,13 @@ public class HbaseAdapter implements CanalOuterAdapter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getDestination(String task) {
|
||||||
|
MappingConfig config = hbaseMapping.get(task);
|
||||||
|
if (config != null && config.getHbaseMapping() != null) {
|
||||||
|
return config.getHbaseMapping().getDestination();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,35 +5,45 @@ import java.util.*;
|
|||||||
/**
|
/**
|
||||||
* HBase表映射配置
|
* HBase表映射配置
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-21 下午06:45:49
|
* @author rewerma 2018-8-21 下午06:45:49
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class MappingConfig {
|
public class MappingConfig {
|
||||||
|
|
||||||
private HbaseOrm hbaseOrm;
|
private String dataSourceKey; // 数据源key
|
||||||
|
|
||||||
public HbaseOrm getHbaseOrm() {
|
private HbaseMapping hbaseMapping; // hbase映射配置
|
||||||
return hbaseOrm;
|
|
||||||
|
public String getDataSourceKey() {
|
||||||
|
return dataSourceKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setHbaseOrm(HbaseOrm hbaseOrm) {
|
public void setDataSourceKey(String dataSourceKey) {
|
||||||
this.hbaseOrm = hbaseOrm;
|
this.dataSourceKey = dataSourceKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public HbaseMapping getHbaseMapping() {
|
||||||
|
return hbaseMapping;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setHbaseMapping(HbaseMapping hbaseMapping) {
|
||||||
|
this.hbaseMapping = hbaseMapping;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void validate() {
|
public void validate() {
|
||||||
if (hbaseOrm.database == null || hbaseOrm.database.isEmpty()) {
|
if (hbaseMapping.database == null || hbaseMapping.database.isEmpty()) {
|
||||||
throw new NullPointerException("hbaseOrm.database");
|
throw new NullPointerException("hbaseMapping.database");
|
||||||
}
|
}
|
||||||
if (hbaseOrm.table == null || hbaseOrm.table.isEmpty()) {
|
if (hbaseMapping.table == null || hbaseMapping.table.isEmpty()) {
|
||||||
throw new NullPointerException("hbaseOrm.table");
|
throw new NullPointerException("hbaseMapping.table");
|
||||||
}
|
}
|
||||||
if (hbaseOrm.hbaseTable == null || hbaseOrm.hbaseTable.isEmpty()) {
|
if (hbaseMapping.hbaseTable == null || hbaseMapping.hbaseTable.isEmpty()) {
|
||||||
throw new NullPointerException("hbaseOrm.hbaseTable");
|
throw new NullPointerException("hbaseMapping.hbaseTable");
|
||||||
}
|
}
|
||||||
if (hbaseOrm.mode == null) {
|
if (hbaseMapping.mode == null) {
|
||||||
throw new NullPointerException("hbaseOrm.mode");
|
throw new NullPointerException("hbaseMapping.mode");
|
||||||
}
|
}
|
||||||
if (hbaseOrm.rowKey != null && hbaseOrm.rowKeyColumn != null) {
|
if (hbaseMapping.rowKey != null && hbaseMapping.rowKeyColumn != null) {
|
||||||
throw new RuntimeException("已配置了复合主键作为RowKey,无需再指定RowKey列");
|
throw new RuntimeException("已配置了复合主键作为RowKey,无需再指定RowKey列");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -45,12 +55,12 @@ public class MappingConfig {
|
|||||||
|
|
||||||
MappingConfig config = (MappingConfig) o;
|
MappingConfig config = (MappingConfig) o;
|
||||||
|
|
||||||
return hbaseOrm != null ? hbaseOrm.equals(config.hbaseOrm) : config.hbaseOrm == null;
|
return hbaseMapping != null ? hbaseMapping.equals(config.hbaseMapping) : config.hbaseMapping == null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return hbaseOrm != null ? hbaseOrm.hashCode() : 0;
|
return hbaseMapping != null ? hbaseMapping.hashCode() : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class ColumnItem {
|
public static class ColumnItem {
|
||||||
@@ -130,24 +140,26 @@ public class MappingConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class HbaseOrm {
|
public static class HbaseMapping {
|
||||||
|
|
||||||
private Mode mode = Mode.STRING;
|
private Mode mode = Mode.STRING; // hbase默认转换格式
|
||||||
private String database;
|
private String destination; // canal实例或MQ的topic
|
||||||
private String table;
|
private String database; // 数据库名或schema名
|
||||||
private String hbaseTable;
|
private String table; // 表面名
|
||||||
private String family = "CF";
|
private String hbaseTable; // hbase表名
|
||||||
private boolean uppercaseQualifier = true;
|
private String family = "CF"; // 默认统一column family
|
||||||
|
private boolean uppercaseQualifier = true; // 是否转大写
|
||||||
private boolean autoCreateTable = false; // 同步时HBase中表不存在的情况下自动建表
|
private boolean autoCreateTable = false; // 同步时HBase中表不存在的情况下自动建表
|
||||||
private String rowKey; // 指定复合主键为rowKey
|
private String rowKey; // 指定复合主键为rowKey
|
||||||
private Map<String, String> columns;
|
private Map<String, String> columns; // 字段映射
|
||||||
private ColumnItem rowKeyColumn;
|
private List<String> excludeColumns; // 不映射的字段
|
||||||
private String etlCondition;
|
private ColumnItem rowKeyColumn; // rowKey字段
|
||||||
|
private String etlCondition; // etl条件sql
|
||||||
|
|
||||||
private Map<String, ColumnItem> columnItems = new LinkedHashMap<>();
|
private Map<String, ColumnItem> columnItems = new LinkedHashMap<>(); // 转换后的字段映射列表
|
||||||
private Set<String> families = new LinkedHashSet<>();
|
private Set<String> families = new LinkedHashSet<>(); // column family列表
|
||||||
private int readBatch = 5000;
|
private int readBatch = 5000;
|
||||||
private int commitBatch = 5000;
|
private int commitBatch = 5000; // etl等批量提交大小
|
||||||
|
|
||||||
public Mode getMode() {
|
public Mode getMode() {
|
||||||
return mode;
|
return mode;
|
||||||
@@ -157,6 +169,14 @@ public class MappingConfig {
|
|||||||
this.mode = mode;
|
this.mode = mode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public String getDestination() {
|
||||||
|
return destination;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDestination(String destination) {
|
||||||
|
this.destination = destination;
|
||||||
|
}
|
||||||
|
|
||||||
public String getDatabase() {
|
public String getDatabase() {
|
||||||
return database;
|
return database;
|
||||||
}
|
}
|
||||||
@@ -273,6 +293,14 @@ public class MappingConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<String> getExcludeColumns() {
|
||||||
|
return excludeColumns;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExcludeColumns(List<String> excludeColumns) {
|
||||||
|
this.excludeColumns = excludeColumns;
|
||||||
|
}
|
||||||
|
|
||||||
public String getFamily() {
|
public String getFamily() {
|
||||||
return family;
|
return family;
|
||||||
}
|
}
|
||||||
@@ -321,10 +349,10 @@ public class MappingConfig {
|
|||||||
if (this == o) return true;
|
if (this == o) return true;
|
||||||
if (o == null || getClass() != o.getClass()) return false;
|
if (o == null || getClass() != o.getClass()) return false;
|
||||||
|
|
||||||
HbaseOrm hbaseOrm = (HbaseOrm) o;
|
HbaseMapping hbaseMapping = (HbaseMapping) o;
|
||||||
|
|
||||||
if (table != null ? !table.equals(hbaseOrm.table) : hbaseOrm.table != null) return false;
|
if (table != null ? !table.equals(hbaseMapping.table) : hbaseMapping.table != null) return false;
|
||||||
return hbaseTable != null ? hbaseTable.equals(hbaseOrm.hbaseTable) : hbaseOrm.hbaseTable == null;
|
return hbaseTable != null ? hbaseTable.equals(hbaseMapping.hbaseTable) : hbaseMapping.hbaseTable == null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import java.io.File;
|
|||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -12,21 +13,19 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.yaml.snakeyaml.Yaml;
|
import org.yaml.snakeyaml.Yaml;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.AdapterConfigs;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HBase表映射配置加载器
|
* HBase表映射配置加载器
|
||||||
* <p>
|
|
||||||
* 配置统一从hbase-mapping/configs.conf文件作为入口, 该文件包含所有表映射配置的名称或者文件名列表。
|
|
||||||
* 每个对应的表配置可以yml配置文件或者以database.table为配置名的简化形式
|
|
||||||
* </p>
|
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-21 下午06:45:49
|
* @author rewerma 2018-8-21 下午06:45:49
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class MappingConfigLoader {
|
public class MappingConfigLoader {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(MappingConfigLoader.class);
|
private static Logger logger = LoggerFactory.getLogger(MappingConfigLoader.class);
|
||||||
|
|
||||||
private static final String BASE_PATH = "hbase-mapping/";
|
private static final String BASE_PATH = "hbase";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 加载HBase表映射配置
|
* 加载HBase表映射配置
|
||||||
@@ -35,12 +34,11 @@ public class MappingConfigLoader {
|
|||||||
*/
|
*/
|
||||||
public static Map<String, MappingConfig> load() {
|
public static Map<String, MappingConfig> load() {
|
||||||
logger.info("## Start loading mapping config ... ");
|
logger.info("## Start loading mapping config ... ");
|
||||||
String mappingConfigContent = readConfigContent(BASE_PATH + "configs.conf");
|
|
||||||
|
|
||||||
Map<String, MappingConfig> result = new LinkedHashMap<>();
|
Map<String, MappingConfig> result = new LinkedHashMap<>();
|
||||||
|
|
||||||
String[] configLines = mappingConfigContent.split("\n");
|
Collection<String> configs = AdapterConfigs.get("hbase");
|
||||||
for (String c : configLines) {
|
for (String c : configs) {
|
||||||
if (c == null) {
|
if (c == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -74,6 +72,7 @@ public class MappingConfigLoader {
|
|||||||
String[] dbTable;
|
String[] dbTable;
|
||||||
if (dsKey == null) {
|
if (dsKey == null) {
|
||||||
dbTable = srcMeta.split("\\.");
|
dbTable = srcMeta.split("\\.");
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
dbTable = srcMeta.split("@")[0].split("\\.");
|
dbTable = srcMeta.split("@")[0].split("\\.");
|
||||||
}
|
}
|
||||||
@@ -81,21 +80,22 @@ public class MappingConfigLoader {
|
|||||||
if (dbTable.length == 2) {
|
if (dbTable.length == 2) {
|
||||||
config = new MappingConfig();
|
config = new MappingConfig();
|
||||||
|
|
||||||
MappingConfig.HbaseOrm hbaseOrm = new MappingConfig.HbaseOrm();
|
MappingConfig.HbaseMapping hbaseMapping = new MappingConfig.HbaseMapping();
|
||||||
hbaseOrm.setHbaseTable(dbTable[0].toUpperCase() + "." + dbTable[1].toUpperCase());
|
hbaseMapping.setHbaseTable(dbTable[0].toUpperCase() + "." + dbTable[1].toUpperCase());
|
||||||
hbaseOrm.setAutoCreateTable(true);
|
hbaseMapping.setAutoCreateTable(true);
|
||||||
hbaseOrm.setDatabase(dbTable[0]);
|
hbaseMapping.setDatabase(dbTable[0]);
|
||||||
hbaseOrm.setTable(dbTable[1]);
|
hbaseMapping.setTable(dbTable[1]);
|
||||||
hbaseOrm.setMode(MappingConfig.Mode.STRING);
|
hbaseMapping.setMode(MappingConfig.Mode.PHOENIX);
|
||||||
hbaseOrm.setRowKey(rowKey);
|
hbaseMapping.setRowKey(rowKey);
|
||||||
// 有定义rowKey
|
// 有定义rowKey
|
||||||
if (rowKey != null) {
|
if (rowKey != null) {
|
||||||
MappingConfig.ColumnItem columnItem = new MappingConfig.ColumnItem();
|
MappingConfig.ColumnItem columnItem = new MappingConfig.ColumnItem();
|
||||||
columnItem.setRowKey(true);
|
columnItem.setRowKey(true);
|
||||||
columnItem.setColumn(rowKey);
|
columnItem.setColumn(rowKey);
|
||||||
hbaseOrm.setRowKeyColumn(columnItem);
|
hbaseMapping.setRowKeyColumn(columnItem);
|
||||||
}
|
}
|
||||||
config.setHbaseOrm(hbaseOrm);
|
config.setHbaseMapping(hbaseMapping);
|
||||||
|
config.setDataSourceKey(dsKey);
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
throw new RuntimeException(String.format("配置项[%s]内容为空, 或格式不符合database.table", c));
|
throw new RuntimeException(String.format("配置项[%s]内容为空, 或格式不符合database.table", c));
|
||||||
|
|||||||
@@ -0,0 +1,385 @@
|
|||||||
|
package com.alibaba.otter.canal.client.adapter.hbase.service;
|
||||||
|
|
||||||
|
import java.sql.*;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
import org.apache.hadoop.hbase.util.Bytes;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.config.MappingConfig;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.hbase.support.*;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.JdbcTypeUtil;
|
||||||
|
import com.google.common.base.Joiner;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HBase ETL 操作业务类
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class HbaseEtlService {
|
||||||
|
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(HbaseEtlService.class);
|
||||||
|
|
||||||
|
public static Object sqlRS(DataSource ds, String sql, Function<ResultSet, Object> fun) throws SQLException {
|
||||||
|
Connection conn = null;
|
||||||
|
Statement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
try {
|
||||||
|
conn = ds.getConnection();
|
||||||
|
stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
|
||||||
|
stmt.setFetchSize(Integer.MIN_VALUE);
|
||||||
|
rs = stmt.executeQuery(sql);
|
||||||
|
return fun.apply(rs);
|
||||||
|
} finally {
|
||||||
|
if (rs != null) {
|
||||||
|
try {
|
||||||
|
rs.close();
|
||||||
|
} catch (SQLException e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (stmt != null) {
|
||||||
|
try {
|
||||||
|
stmt.close();
|
||||||
|
} catch (SQLException e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (conn != null) {
|
||||||
|
try {
|
||||||
|
conn.close();
|
||||||
|
} catch (SQLException e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rs = null;
|
||||||
|
stmt = null;
|
||||||
|
conn = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 建表
|
||||||
|
*
|
||||||
|
* @param hbaseTemplate
|
||||||
|
* @param config
|
||||||
|
*/
|
||||||
|
public static void createTable(HbaseTemplate hbaseTemplate, MappingConfig config) {
|
||||||
|
try {
|
||||||
|
// 判断hbase表是否存在,不存在则建表
|
||||||
|
MappingConfig.HbaseMapping hbaseMapping = config.getHbaseMapping();
|
||||||
|
if (!hbaseTemplate.tableExists(hbaseMapping.getHbaseTable())) {
|
||||||
|
hbaseTemplate.createTable(hbaseMapping.getHbaseTable(), hbaseMapping.getFamily());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导入数据
|
||||||
|
*
|
||||||
|
* @param ds 数据源
|
||||||
|
* @param hbaseTemplate hbaseTemplate
|
||||||
|
* @param config 配置
|
||||||
|
* @param params 筛选条件
|
||||||
|
* @return 导入结果
|
||||||
|
*/
|
||||||
|
public static EtlResult importData(DataSource ds, HbaseTemplate hbaseTemplate, MappingConfig config,
|
||||||
|
List<String> params) {
|
||||||
|
EtlResult etlResult = new EtlResult();
|
||||||
|
AtomicLong successCount = new AtomicLong();
|
||||||
|
List<String> errMsg = new ArrayList<>();
|
||||||
|
String hbaseTable = "";
|
||||||
|
try {
|
||||||
|
if (config == null) {
|
||||||
|
logger.error("Config is null!");
|
||||||
|
etlResult.setSucceeded(false);
|
||||||
|
etlResult.setErrorMessage("Config is null!");
|
||||||
|
return etlResult;
|
||||||
|
}
|
||||||
|
MappingConfig.HbaseMapping hbaseMapping = config.getHbaseMapping();
|
||||||
|
hbaseTable = hbaseMapping.getHbaseTable();
|
||||||
|
|
||||||
|
long start = System.currentTimeMillis();
|
||||||
|
|
||||||
|
if (params != null && params.size() == 1 && "rebuild".equalsIgnoreCase(params.get(0))) {
|
||||||
|
logger.info(hbaseMapping.getHbaseTable() + " rebuild is starting!");
|
||||||
|
// 如果表存在则删除
|
||||||
|
if (hbaseTemplate.tableExists(hbaseMapping.getHbaseTable())) {
|
||||||
|
hbaseTemplate.disableTable(hbaseMapping.getHbaseTable());
|
||||||
|
hbaseTemplate.deleteTable(hbaseMapping.getHbaseTable());
|
||||||
|
}
|
||||||
|
params = null;
|
||||||
|
} else {
|
||||||
|
logger.info(hbaseMapping.getHbaseTable() + " etl is starting!");
|
||||||
|
}
|
||||||
|
createTable(hbaseTemplate, config);
|
||||||
|
|
||||||
|
// 拼接sql
|
||||||
|
String sql = "SELECT * FROM " + config.getHbaseMapping().getDatabase() + "." + hbaseMapping.getTable();
|
||||||
|
|
||||||
|
// 拼接条件
|
||||||
|
if (params != null && params.size() == 1 && hbaseMapping.getEtlCondition() == null) {
|
||||||
|
AtomicBoolean stExists = new AtomicBoolean(false);
|
||||||
|
// 验证是否有SYS_TIME字段
|
||||||
|
sqlRS(ds, sql, rs -> {
|
||||||
|
try {
|
||||||
|
ResultSetMetaData rsmd = rs.getMetaData();
|
||||||
|
int cnt = rsmd.getColumnCount();
|
||||||
|
for (int i = 1; i <= cnt; i++) {
|
||||||
|
String columnName = rsmd.getColumnName(i);
|
||||||
|
if ("SYS_TIME".equalsIgnoreCase(columnName)) {
|
||||||
|
stExists.set(true);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
if (stExists.get()) {
|
||||||
|
sql += " WHERE SYS_TIME >= '" + params.get(0) + "' ";
|
||||||
|
}
|
||||||
|
} else if (hbaseMapping.getEtlCondition() != null && params != null) {
|
||||||
|
String etlCondition = hbaseMapping.getEtlCondition();
|
||||||
|
int size = params.size();
|
||||||
|
for (int i = 0; i < size; i++) {
|
||||||
|
etlCondition = etlCondition.replace("{" + i + "}", params.get(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
sql += " " + etlCondition;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取总数
|
||||||
|
String countSql = "SELECT COUNT(1) FROM ( " + sql + ") _CNT ";
|
||||||
|
long cnt = (Long) sqlRS(ds, countSql, rs -> {
|
||||||
|
Long count = null;
|
||||||
|
try {
|
||||||
|
if (rs.next()) {
|
||||||
|
count = ((Number) rs.getObject(1)).longValue();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
return count == null ? 0 : count;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 当大于1万条记录时开启多线程
|
||||||
|
if (cnt >= 10000) {
|
||||||
|
int threadCount = 3;
|
||||||
|
long perThreadCnt = cnt / threadCount;
|
||||||
|
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
|
||||||
|
List<Future<Boolean>> futures = new ArrayList<>(threadCount);
|
||||||
|
for (int i = 0; i < threadCount; i++) {
|
||||||
|
long offset = i * perThreadCnt;
|
||||||
|
Long size = null;
|
||||||
|
if (i != threadCount - 1) {
|
||||||
|
size = perThreadCnt;
|
||||||
|
}
|
||||||
|
String sqlFinal;
|
||||||
|
if (size != null) {
|
||||||
|
sqlFinal = sql + " LIMIT " + offset + "," + size;
|
||||||
|
} else {
|
||||||
|
sqlFinal = sql + " LIMIT " + offset + "," + cnt;
|
||||||
|
}
|
||||||
|
Future<Boolean> future = executor
|
||||||
|
.submit(() -> executeSqlImport(ds, sqlFinal, hbaseMapping, hbaseTemplate, successCount, errMsg));
|
||||||
|
futures.add(future);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Future<Boolean> future : futures) {
|
||||||
|
future.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
executor.shutdown();
|
||||||
|
} else {
|
||||||
|
executeSqlImport(ds, sql, hbaseMapping, hbaseTemplate, successCount, errMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
hbaseMapping.getHbaseTable() + " etl completed in: " + (System.currentTimeMillis() - start) / 1000 + "s!");
|
||||||
|
|
||||||
|
etlResult.setResultMessage("导入HBase表 " + hbaseMapping.getHbaseTable() + " 数据:" + successCount.get() + " 条");
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
errMsg.add(hbaseTable + " etl failed! ==>" + e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (errMsg.isEmpty()) {
|
||||||
|
etlResult.setSucceeded(true);
|
||||||
|
} else {
|
||||||
|
etlResult.setErrorMessage(Joiner.on("\n").join(errMsg));
|
||||||
|
}
|
||||||
|
return etlResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行导入
|
||||||
|
*
|
||||||
|
* @param ds
|
||||||
|
* @param sql
|
||||||
|
* @param hbaseMapping
|
||||||
|
* @param hbaseTemplate
|
||||||
|
* @param successCount
|
||||||
|
* @param errMsg
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
private static boolean executeSqlImport(DataSource ds, String sql, MappingConfig.HbaseMapping hbaseMapping,
|
||||||
|
HbaseTemplate hbaseTemplate, AtomicLong successCount, List<String> errMsg) {
|
||||||
|
try {
|
||||||
|
sqlRS(ds, sql, rs -> {
|
||||||
|
int i = 1;
|
||||||
|
|
||||||
|
try {
|
||||||
|
boolean complete = false;
|
||||||
|
List<HRow> rows = new ArrayList<>();
|
||||||
|
String[] rowKeyColumns = null;
|
||||||
|
if (hbaseMapping.getRowKey() != null) {
|
||||||
|
rowKeyColumns = hbaseMapping.getRowKey().trim().split(",");
|
||||||
|
}
|
||||||
|
while (rs.next()) {
|
||||||
|
int cc = rs.getMetaData().getColumnCount();
|
||||||
|
int[] jdbcTypes = new int[cc];
|
||||||
|
Class<?>[] classes = new Class[cc];
|
||||||
|
for (int j = 1; j <= cc; j++) {
|
||||||
|
int jdbcType = rs.getMetaData().getColumnType(j);
|
||||||
|
jdbcTypes[j - 1] = jdbcType;
|
||||||
|
classes[j - 1] = JdbcTypeUtil.jdbcType2javaType(jdbcType);
|
||||||
|
}
|
||||||
|
HRow row = new HRow();
|
||||||
|
|
||||||
|
if (rowKeyColumns != null) {
|
||||||
|
// 取rowKey字段拼接
|
||||||
|
StringBuilder rowKeyVale = new StringBuilder();
|
||||||
|
for (String rowKeyColumnName : rowKeyColumns) {
|
||||||
|
Object obj = rs.getObject(rowKeyColumnName);
|
||||||
|
if (obj != null) {
|
||||||
|
rowKeyVale.append(obj.toString());
|
||||||
|
}
|
||||||
|
rowKeyVale.append("|");
|
||||||
|
}
|
||||||
|
int len = rowKeyVale.length();
|
||||||
|
if (len > 0) {
|
||||||
|
rowKeyVale.delete(len - 1, len);
|
||||||
|
}
|
||||||
|
row.setRowKey(Bytes.toBytes(rowKeyVale.toString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int j = 1; j <= cc; j++) {
|
||||||
|
String columnName = rs.getMetaData().getColumnName(j);
|
||||||
|
|
||||||
|
Object val = JdbcTypeUtil.getRSData(rs, columnName, jdbcTypes[j - 1]);
|
||||||
|
if (val == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
MappingConfig.ColumnItem columnItem = hbaseMapping.getColumnItems().get(columnName);
|
||||||
|
// 没有配置映射
|
||||||
|
if (columnItem == null) {
|
||||||
|
String family = hbaseMapping.getFamily();
|
||||||
|
String qualifile = columnName;
|
||||||
|
if (hbaseMapping.isUppercaseQualifier()) {
|
||||||
|
qualifile = qualifile.toUpperCase();
|
||||||
|
}
|
||||||
|
if (MappingConfig.Mode.STRING == hbaseMapping.getMode()) {
|
||||||
|
if (hbaseMapping.getRowKey() == null && j == 1) {
|
||||||
|
row.setRowKey(Bytes.toBytes(val.toString()));
|
||||||
|
} else {
|
||||||
|
row.addCell(family, qualifile, Bytes.toBytes(val.toString()));
|
||||||
|
}
|
||||||
|
} else if (MappingConfig.Mode.NATIVE == hbaseMapping.getMode()) {
|
||||||
|
Type type = Type.getType(classes[j - 1]);
|
||||||
|
if (hbaseMapping.getRowKey() == null && j == 1) {
|
||||||
|
row.setRowKey(TypeUtil.toBytes(val, type));
|
||||||
|
} else {
|
||||||
|
row.addCell(family, qualifile, TypeUtil.toBytes(val, type));
|
||||||
|
}
|
||||||
|
} else if (MappingConfig.Mode.PHOENIX == hbaseMapping.getMode()) {
|
||||||
|
PhType phType = PhType.getType(classes[j - 1]);
|
||||||
|
if (hbaseMapping.getRowKey() == null && j == 1) {
|
||||||
|
row.setRowKey(PhTypeUtil.toBytes(val, phType));
|
||||||
|
} else {
|
||||||
|
row.addCell(family, qualifile, PhTypeUtil.toBytes(val, phType));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 如果不需要类型转换
|
||||||
|
if (columnItem.getType() == null || "".equals(columnItem.getType())) {
|
||||||
|
if (val instanceof java.sql.Date) {
|
||||||
|
SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd");
|
||||||
|
val = dateFmt.format((Date) val);
|
||||||
|
} else if (val instanceof Timestamp) {
|
||||||
|
SimpleDateFormat datetimeFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||||
|
val = datetimeFmt.format((Date) val);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] valBytes = Bytes.toBytes(val.toString());
|
||||||
|
if (columnItem.isRowKey()) {
|
||||||
|
row.setRowKey(valBytes);
|
||||||
|
} else {
|
||||||
|
row.addCell(columnItem.getFamily(), columnItem.getQualifier(), valBytes);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
PhType phType = PhType.getType(columnItem.getType());
|
||||||
|
if (columnItem.isRowKey()) {
|
||||||
|
row.setRowKey(PhTypeUtil.toBytes(val, phType));
|
||||||
|
} else {
|
||||||
|
row.addCell(columnItem.getFamily(),
|
||||||
|
columnItem.getQualifier(),
|
||||||
|
PhTypeUtil.toBytes(val, phType));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (row.getRowKey() == null) throw new RuntimeException("RowKey 值为空");
|
||||||
|
|
||||||
|
rows.add(row);
|
||||||
|
complete = false;
|
||||||
|
if (i % hbaseMapping.getCommitBatch() == 0 && !rows.isEmpty()) {
|
||||||
|
hbaseTemplate.puts(hbaseMapping.getHbaseTable(), rows);
|
||||||
|
rows.clear();
|
||||||
|
complete = true;
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
successCount.incrementAndGet();
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("successful import count:" + successCount.get());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!complete && !rows.isEmpty()) {
|
||||||
|
hbaseTemplate.puts(hbaseMapping.getHbaseTable(), rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(hbaseMapping.getHbaseTable() + " etl failed! ==>" + e.getMessage(), e);
|
||||||
|
errMsg.add(hbaseMapping.getHbaseTable() + " etl failed! ==>" + e.getMessage());
|
||||||
|
// throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ package com.alibaba.otter.canal.client.adapter.hbase.service;
|
|||||||
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
import org.apache.hadoop.hbase.client.Connection;
|
|
||||||
import org.apache.hadoop.hbase.util.Bytes;
|
import org.apache.hadoop.hbase.util.Bytes;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@@ -14,7 +13,7 @@ import com.alibaba.otter.canal.client.adapter.support.Dml;
|
|||||||
/**
|
/**
|
||||||
* HBase同步操作业务
|
* HBase同步操作业务
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-21 下午06:45:49
|
* @author rewerma 2018-8-21 下午06:45:49
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class HbaseSyncService {
|
public class HbaseSyncService {
|
||||||
@@ -23,8 +22,8 @@ public class HbaseSyncService {
|
|||||||
|
|
||||||
private HbaseTemplate hbaseTemplate; // HBase操作模板
|
private HbaseTemplate hbaseTemplate; // HBase操作模板
|
||||||
|
|
||||||
public HbaseSyncService(Connection conn){
|
public HbaseSyncService(HbaseTemplate hbaseTemplate){
|
||||||
hbaseTemplate = new HbaseTemplate(conn);
|
this.hbaseTemplate = hbaseTemplate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void sync(MappingConfig config, Dml dml) {
|
public void sync(MappingConfig config, Dml dml) {
|
||||||
@@ -60,10 +59,11 @@ public class HbaseSyncService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
MappingConfig.HbaseOrm hbaseOrm = config.getHbaseOrm();
|
MappingConfig.HbaseMapping hbaseMapping = config.getHbaseMapping();
|
||||||
|
|
||||||
// if (!validHTable(config)) {
|
// if (!validHTable(config)) {
|
||||||
// logger.error("HBase table '{}' not exists", hbaseOrm.getHbaseTable());
|
// logger.error("HBase table '{}' not exists",
|
||||||
|
// hbaseMapping.getHbaseTable());
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
int i = 1;
|
int i = 1;
|
||||||
@@ -73,28 +73,28 @@ public class HbaseSyncService {
|
|||||||
HRow hRow = new HRow();
|
HRow hRow = new HRow();
|
||||||
|
|
||||||
// 拼接复合rowKey
|
// 拼接复合rowKey
|
||||||
if (hbaseOrm.getRowKey() != null) {
|
if (hbaseMapping.getRowKey() != null) {
|
||||||
String[] rowKeyColumns = hbaseOrm.getRowKey().trim().split(",");
|
String[] rowKeyColumns = hbaseMapping.getRowKey().trim().split(",");
|
||||||
String rowKeyVale = getRowKeys(rowKeyColumns, r);
|
String rowKeyVale = getRowKeys(rowKeyColumns, r);
|
||||||
// params.put("rowKey", Bytes.toBytes(rowKeyVale));
|
// params.put("rowKey", Bytes.toBytes(rowKeyVale));
|
||||||
hRow.setRowKey(Bytes.toBytes(rowKeyVale));
|
hRow.setRowKey(Bytes.toBytes(rowKeyVale));
|
||||||
}
|
}
|
||||||
|
|
||||||
convertData2Row(hbaseOrm, hRow, r);
|
convertData2Row(hbaseMapping, hRow, r);
|
||||||
if (hRow.getRowKey() == null) {
|
if (hRow.getRowKey() == null) {
|
||||||
throw new RuntimeException("empty rowKey");
|
throw new RuntimeException("empty rowKey");
|
||||||
}
|
}
|
||||||
rows.add(hRow);
|
rows.add(hRow);
|
||||||
complete = false;
|
complete = false;
|
||||||
if (i % config.getHbaseOrm().getCommitBatch() == 0 && !rows.isEmpty()) {
|
if (i % config.getHbaseMapping().getCommitBatch() == 0 && !rows.isEmpty()) {
|
||||||
hbaseTemplate.puts(hbaseOrm.getHbaseTable(), rows);
|
hbaseTemplate.puts(hbaseMapping.getHbaseTable(), rows);
|
||||||
rows.clear();
|
rows.clear();
|
||||||
complete = true;
|
complete = true;
|
||||||
}
|
}
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
if (!complete && !rows.isEmpty()) {
|
if (!complete && !rows.isEmpty()) {
|
||||||
hbaseTemplate.puts(hbaseOrm.getHbaseTable(), rows);
|
hbaseTemplate.puts(hbaseMapping.getHbaseTable(), rows);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -102,27 +102,30 @@ public class HbaseSyncService {
|
|||||||
/**
|
/**
|
||||||
* 将Map数据转换为HRow行数据
|
* 将Map数据转换为HRow行数据
|
||||||
*
|
*
|
||||||
* @param hbaseOrm hbase映射配置
|
* @param hbaseMapping hbase映射配置
|
||||||
* @param hRow 行对象
|
* @param hRow 行对象
|
||||||
* @param data Map数据
|
* @param data Map数据
|
||||||
*/
|
*/
|
||||||
private static void convertData2Row(MappingConfig.HbaseOrm hbaseOrm, HRow hRow, Map<String, Object> data) {
|
private static void convertData2Row(MappingConfig.HbaseMapping hbaseMapping, HRow hRow, Map<String, Object> data) {
|
||||||
Map<String, MappingConfig.ColumnItem> columnItems = hbaseOrm.getColumnItems();
|
Map<String, MappingConfig.ColumnItem> columnItems = hbaseMapping.getColumnItems();
|
||||||
int i = 0;
|
int i = 0;
|
||||||
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
||||||
|
if (hbaseMapping.getExcludeColumns() != null && hbaseMapping.getExcludeColumns().contains(entry.getKey())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (entry.getValue() != null) {
|
if (entry.getValue() != null) {
|
||||||
MappingConfig.ColumnItem columnItem = columnItems.get(entry.getKey());
|
MappingConfig.ColumnItem columnItem = columnItems.get(entry.getKey());
|
||||||
|
|
||||||
byte[] bytes = typeConvert(columnItem, hbaseOrm, entry.getValue());
|
byte[] bytes = typeConvert(columnItem, hbaseMapping, entry.getValue());
|
||||||
|
|
||||||
if (columnItem == null) {
|
if (columnItem == null) {
|
||||||
String familyName = hbaseOrm.getFamily();
|
String familyName = hbaseMapping.getFamily();
|
||||||
String qualifier = entry.getKey();
|
String qualifier = entry.getKey();
|
||||||
if (hbaseOrm.isUppercaseQualifier()) {
|
if (hbaseMapping.isUppercaseQualifier()) {
|
||||||
qualifier = qualifier.toUpperCase();
|
qualifier = qualifier.toUpperCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hbaseOrm.getRowKey() == null && i == 0) {
|
if (hbaseMapping.getRowKey() == null && i == 0) {
|
||||||
hRow.setRowKey(bytes);
|
hRow.setRowKey(bytes);
|
||||||
} else {
|
} else {
|
||||||
hRow.addCell(familyName, qualifier, bytes);
|
hRow.addCell(familyName, qualifier, bytes);
|
||||||
@@ -153,14 +156,15 @@ public class HbaseSyncService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
MappingConfig.HbaseOrm hbaseOrm = config.getHbaseOrm();
|
MappingConfig.HbaseMapping hbaseMapping = config.getHbaseMapping();
|
||||||
|
|
||||||
// if (!validHTable(config)) {
|
// if (!validHTable(config)) {
|
||||||
// logger.error("HBase table '{}' not exists", hbaseOrm.getHbaseTable());
|
// logger.error("HBase table '{}' not exists",
|
||||||
|
// hbaseMapping.getHbaseTable());
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
|
|
||||||
MappingConfig.ColumnItem rowKeyColumn = hbaseOrm.getRowKeyColumn();
|
MappingConfig.ColumnItem rowKeyColumn = hbaseMapping.getRowKeyColumn();
|
||||||
int index = 0;
|
int index = 0;
|
||||||
int i = 1;
|
int i = 1;
|
||||||
boolean complete = false;
|
boolean complete = false;
|
||||||
@@ -168,8 +172,8 @@ public class HbaseSyncService {
|
|||||||
out: for (Map<String, Object> r : data) {
|
out: for (Map<String, Object> r : data) {
|
||||||
byte[] rowKeyBytes;
|
byte[] rowKeyBytes;
|
||||||
|
|
||||||
if (hbaseOrm.getRowKey() != null) {
|
if (hbaseMapping.getRowKey() != null) {
|
||||||
String[] rowKeyColumns = hbaseOrm.getRowKey().trim().split(",");
|
String[] rowKeyColumns = hbaseMapping.getRowKey().trim().split(",");
|
||||||
|
|
||||||
// 判断是否有复合主键修改
|
// 判断是否有复合主键修改
|
||||||
for (String updateColumn : old.get(index).keySet()) {
|
for (String updateColumn : old.get(index).keySet()) {
|
||||||
@@ -186,20 +190,23 @@ public class HbaseSyncService {
|
|||||||
rowKeyBytes = Bytes.toBytes(rowKeyVale);
|
rowKeyBytes = Bytes.toBytes(rowKeyVale);
|
||||||
} else if (rowKeyColumn == null) {
|
} else if (rowKeyColumn == null) {
|
||||||
Map<String, Object> rowKey = data.get(0);
|
Map<String, Object> rowKey = data.get(0);
|
||||||
rowKeyBytes = typeConvert(null, hbaseOrm, rowKey.values().iterator().next());
|
rowKeyBytes = typeConvert(null, hbaseMapping, rowKey.values().iterator().next());
|
||||||
} else {
|
} else {
|
||||||
rowKeyBytes = typeConvert(rowKeyColumn, hbaseOrm, r.get(rowKeyColumn.getColumn()));
|
rowKeyBytes = typeConvert(rowKeyColumn, hbaseMapping, r.get(rowKeyColumn.getColumn()));
|
||||||
}
|
}
|
||||||
if (rowKeyBytes == null) throw new RuntimeException("rowKey值为空");
|
if (rowKeyBytes == null) throw new RuntimeException("rowKey值为空");
|
||||||
|
|
||||||
Map<String, MappingConfig.ColumnItem> columnItems = hbaseOrm.getColumnItems();
|
Map<String, MappingConfig.ColumnItem> columnItems = hbaseMapping.getColumnItems();
|
||||||
HRow hRow = new HRow(rowKeyBytes);
|
HRow hRow = new HRow(rowKeyBytes);
|
||||||
for (String updateColumn : old.get(index).keySet()) {
|
for (String updateColumn : old.get(index).keySet()) {
|
||||||
|
if (hbaseMapping.getExcludeColumns() != null && hbaseMapping.getExcludeColumns().contains(updateColumn)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
MappingConfig.ColumnItem columnItem = columnItems.get(updateColumn);
|
MappingConfig.ColumnItem columnItem = columnItems.get(updateColumn);
|
||||||
if (columnItem == null) {
|
if (columnItem == null) {
|
||||||
String family = hbaseOrm.getFamily();
|
String family = hbaseMapping.getFamily();
|
||||||
String qualifier = updateColumn;
|
String qualifier = updateColumn;
|
||||||
if (hbaseOrm.isUppercaseQualifier()) {
|
if (hbaseMapping.isUppercaseQualifier()) {
|
||||||
qualifier = qualifier.toUpperCase();
|
qualifier = qualifier.toUpperCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,7 +215,7 @@ public class HbaseSyncService {
|
|||||||
if (newVal == null) {
|
if (newVal == null) {
|
||||||
hRow.addCell(family, qualifier, null);
|
hRow.addCell(family, qualifier, null);
|
||||||
} else {
|
} else {
|
||||||
hRow.addCell(family, qualifier, typeConvert(null, hbaseOrm, newVal));
|
hRow.addCell(family, qualifier, typeConvert(null, hbaseMapping, newVal));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 排除修改id的情况
|
// 排除修改id的情况
|
||||||
@@ -220,14 +227,14 @@ public class HbaseSyncService {
|
|||||||
} else {
|
} else {
|
||||||
hRow.addCell(columnItem.getFamily(),
|
hRow.addCell(columnItem.getFamily(),
|
||||||
columnItem.getQualifier(),
|
columnItem.getQualifier(),
|
||||||
typeConvert(columnItem, hbaseOrm, newVal));
|
typeConvert(columnItem, hbaseMapping, newVal));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
rows.add(hRow);
|
rows.add(hRow);
|
||||||
complete = false;
|
complete = false;
|
||||||
if (i % config.getHbaseOrm().getCommitBatch() == 0 && !rows.isEmpty()) {
|
if (i % config.getHbaseMapping().getCommitBatch() == 0 && !rows.isEmpty()) {
|
||||||
hbaseTemplate.puts(hbaseOrm.getHbaseTable(), rows);
|
hbaseTemplate.puts(hbaseMapping.getHbaseTable(), rows);
|
||||||
rows.clear();
|
rows.clear();
|
||||||
complete = true;
|
complete = true;
|
||||||
}
|
}
|
||||||
@@ -235,7 +242,7 @@ public class HbaseSyncService {
|
|||||||
index++;
|
index++;
|
||||||
}
|
}
|
||||||
if (!complete && !rows.isEmpty()) {
|
if (!complete && !rows.isEmpty()) {
|
||||||
hbaseTemplate.puts(hbaseOrm.getHbaseTable(), rows);
|
hbaseTemplate.puts(hbaseMapping.getHbaseTable(), rows);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,44 +252,45 @@ public class HbaseSyncService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
MappingConfig.HbaseOrm hbaseOrm = config.getHbaseOrm();
|
MappingConfig.HbaseMapping hbaseMapping = config.getHbaseMapping();
|
||||||
|
|
||||||
// if (!validHTable(config)) {
|
// if (!validHTable(config)) {
|
||||||
// logger.error("HBase table '{}' not exists", hbaseOrm.getHbaseTable());
|
// logger.error("HBase table '{}' not exists",
|
||||||
|
// hbaseMapping.getHbaseTable());
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
|
|
||||||
MappingConfig.ColumnItem rowKeyColumn = hbaseOrm.getRowKeyColumn();
|
MappingConfig.ColumnItem rowKeyColumn = hbaseMapping.getRowKeyColumn();
|
||||||
boolean complete = false;
|
boolean complete = false;
|
||||||
int i = 1;
|
int i = 1;
|
||||||
Set<byte[]> rowKeys = new HashSet<>();
|
Set<byte[]> rowKeys = new HashSet<>();
|
||||||
for (Map<String, Object> r : data) {
|
for (Map<String, Object> r : data) {
|
||||||
byte[] rowKeyBytes;
|
byte[] rowKeyBytes;
|
||||||
|
|
||||||
if (hbaseOrm.getRowKey() != null) {
|
if (hbaseMapping.getRowKey() != null) {
|
||||||
String[] rowKeyColumns = hbaseOrm.getRowKey().trim().split(",");
|
String[] rowKeyColumns = hbaseMapping.getRowKey().trim().split(",");
|
||||||
String rowKeyVale = getRowKeys(rowKeyColumns, r);
|
String rowKeyVale = getRowKeys(rowKeyColumns, r);
|
||||||
rowKeyBytes = Bytes.toBytes(rowKeyVale);
|
rowKeyBytes = Bytes.toBytes(rowKeyVale);
|
||||||
} else if (rowKeyColumn == null) {
|
} else if (rowKeyColumn == null) {
|
||||||
// 如果不需要类型转换
|
// 如果不需要类型转换
|
||||||
Map<String, Object> rowKey = data.get(0);
|
Map<String, Object> rowKey = data.get(0);
|
||||||
rowKeyBytes = typeConvert(null, hbaseOrm, rowKey.values().iterator().next());
|
rowKeyBytes = typeConvert(null, hbaseMapping, rowKey.values().iterator().next());
|
||||||
} else {
|
} else {
|
||||||
Object val = r.get(rowKeyColumn.getColumn());
|
Object val = r.get(rowKeyColumn.getColumn());
|
||||||
rowKeyBytes = typeConvert(rowKeyColumn, hbaseOrm, val);
|
rowKeyBytes = typeConvert(rowKeyColumn, hbaseMapping, val);
|
||||||
}
|
}
|
||||||
if (rowKeyBytes == null) throw new RuntimeException("rowKey值为空");
|
if (rowKeyBytes == null) throw new RuntimeException("rowKey值为空");
|
||||||
rowKeys.add(rowKeyBytes);
|
rowKeys.add(rowKeyBytes);
|
||||||
complete = false;
|
complete = false;
|
||||||
if (i % config.getHbaseOrm().getCommitBatch() == 0 && !rowKeys.isEmpty()) {
|
if (i % config.getHbaseMapping().getCommitBatch() == 0 && !rowKeys.isEmpty()) {
|
||||||
hbaseTemplate.deletes(hbaseOrm.getHbaseTable(), rowKeys);
|
hbaseTemplate.deletes(hbaseMapping.getHbaseTable(), rowKeys);
|
||||||
rowKeys.clear();
|
rowKeys.clear();
|
||||||
complete = true;
|
complete = true;
|
||||||
}
|
}
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
if (!complete && !rowKeys.isEmpty()) {
|
if (!complete && !rowKeys.isEmpty()) {
|
||||||
hbaseTemplate.deletes(hbaseOrm.getHbaseTable(), rowKeys);
|
hbaseTemplate.deletes(hbaseMapping.getHbaseTable(), rowKeys);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -292,9 +300,9 @@ public class HbaseSyncService {
|
|||||||
if (old == null || old.isEmpty() || data == null || data.isEmpty()) {
|
if (old == null || old.isEmpty() || data == null || data.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
MappingConfig.HbaseOrm hbaseOrm = config.getHbaseOrm();
|
MappingConfig.HbaseMapping hbaseMapping = config.getHbaseMapping();
|
||||||
|
|
||||||
String[] rowKeyColumns = hbaseOrm.getRowKey().trim().split(",");
|
String[] rowKeyColumns = hbaseMapping.getRowKey().trim().split(",");
|
||||||
|
|
||||||
int index = 0;
|
int index = 0;
|
||||||
int i = 1;
|
int i = 1;
|
||||||
@@ -335,13 +343,13 @@ public class HbaseSyncService {
|
|||||||
|
|
||||||
rowKeys.add(oldRowKeyBytes);
|
rowKeys.add(oldRowKeyBytes);
|
||||||
HRow row = new HRow(newRowKeyBytes);
|
HRow row = new HRow(newRowKeyBytes);
|
||||||
convertData2Row(hbaseOrm, row, r);
|
convertData2Row(hbaseMapping, row, r);
|
||||||
rows.add(row);
|
rows.add(row);
|
||||||
complete = false;
|
complete = false;
|
||||||
if (i % config.getHbaseOrm().getCommitBatch() == 0 && !rows.isEmpty()) {
|
if (i % config.getHbaseMapping().getCommitBatch() == 0 && !rows.isEmpty()) {
|
||||||
hbaseTemplate.deletes(hbaseOrm.getHbaseTable(), rowKeys);
|
hbaseTemplate.deletes(hbaseMapping.getHbaseTable(), rowKeys);
|
||||||
|
|
||||||
hbaseTemplate.puts(hbaseOrm.getHbaseTable(), rows);
|
hbaseTemplate.puts(hbaseMapping.getHbaseTable(), rows);
|
||||||
rowKeys.clear();
|
rowKeys.clear();
|
||||||
rows.clear();
|
rows.clear();
|
||||||
complete = true;
|
complete = true;
|
||||||
@@ -350,8 +358,8 @@ public class HbaseSyncService {
|
|||||||
index++;
|
index++;
|
||||||
}
|
}
|
||||||
if (!complete && !rows.isEmpty()) {
|
if (!complete && !rows.isEmpty()) {
|
||||||
hbaseTemplate.deletes(hbaseOrm.getHbaseTable(), rowKeys);
|
hbaseTemplate.deletes(hbaseMapping.getHbaseTable(), rowKeys);
|
||||||
hbaseTemplate.puts(hbaseOrm.getHbaseTable(), rows);
|
hbaseTemplate.puts(hbaseMapping.getHbaseTable(), rows);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,32 +367,32 @@ public class HbaseSyncService {
|
|||||||
* 根据对应的类型进行转换
|
* 根据对应的类型进行转换
|
||||||
*
|
*
|
||||||
* @param columnItem 列项配置
|
* @param columnItem 列项配置
|
||||||
* @param hbaseOrm hbase映射配置
|
* @param hbaseMapping hbase映射配置
|
||||||
* @param value 值
|
* @param value 值
|
||||||
* @return 复合字段rowKey
|
* @return 复合字段rowKey
|
||||||
*/
|
*/
|
||||||
private static byte[] typeConvert(MappingConfig.ColumnItem columnItem, MappingConfig.HbaseOrm hbaseOrm,
|
private static byte[] typeConvert(MappingConfig.ColumnItem columnItem, MappingConfig.HbaseMapping hbaseMapping,
|
||||||
Object value) {
|
Object value) {
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
byte[] bytes = null;
|
byte[] bytes = null;
|
||||||
if (columnItem == null || columnItem.getType() == null || "".equals(columnItem.getType())) {
|
if (columnItem == null || columnItem.getType() == null || "".equals(columnItem.getType())) {
|
||||||
if (MappingConfig.Mode.STRING == hbaseOrm.getMode()) {
|
if (MappingConfig.Mode.STRING == hbaseMapping.getMode()) {
|
||||||
bytes = Bytes.toBytes(value.toString());
|
bytes = Bytes.toBytes(value.toString());
|
||||||
} else if (MappingConfig.Mode.NATIVE == hbaseOrm.getMode()) {
|
} else if (MappingConfig.Mode.NATIVE == hbaseMapping.getMode()) {
|
||||||
bytes = TypeUtil.toBytes(value);
|
bytes = TypeUtil.toBytes(value);
|
||||||
} else if (MappingConfig.Mode.PHOENIX == hbaseOrm.getMode()) {
|
} else if (MappingConfig.Mode.PHOENIX == hbaseMapping.getMode()) {
|
||||||
PhType phType = PhType.getType(value.getClass());
|
PhType phType = PhType.getType(value.getClass());
|
||||||
bytes = PhTypeUtil.toBytes(value, phType);
|
bytes = PhTypeUtil.toBytes(value, phType);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (hbaseOrm.getMode() == MappingConfig.Mode.STRING) {
|
if (hbaseMapping.getMode() == MappingConfig.Mode.STRING) {
|
||||||
bytes = Bytes.toBytes(value.toString());
|
bytes = Bytes.toBytes(value.toString());
|
||||||
} else if (hbaseOrm.getMode() == MappingConfig.Mode.NATIVE) {
|
} else if (hbaseMapping.getMode() == MappingConfig.Mode.NATIVE) {
|
||||||
Type type = Type.getType(columnItem.getType());
|
Type type = Type.getType(columnItem.getType());
|
||||||
bytes = TypeUtil.toBytes(value, type);
|
bytes = TypeUtil.toBytes(value, type);
|
||||||
} else if (hbaseOrm.getMode() == MappingConfig.Mode.PHOENIX) {
|
} else if (hbaseMapping.getMode() == MappingConfig.Mode.PHOENIX) {
|
||||||
PhType phType = PhType.getType(columnItem.getType());
|
PhType phType = PhType.getType(columnItem.getType());
|
||||||
bytes = PhTypeUtil.toBytes(value, phType);
|
bytes = PhTypeUtil.toBytes(value, phType);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,11 @@ import java.util.Set;
|
|||||||
import org.apache.hadoop.hbase.HColumnDescriptor;
|
import org.apache.hadoop.hbase.HColumnDescriptor;
|
||||||
import org.apache.hadoop.hbase.HTableDescriptor;
|
import org.apache.hadoop.hbase.HTableDescriptor;
|
||||||
import org.apache.hadoop.hbase.TableName;
|
import org.apache.hadoop.hbase.TableName;
|
||||||
import org.apache.hadoop.hbase.client.*;
|
import org.apache.hadoop.hbase.client.Connection;
|
||||||
|
import org.apache.hadoop.hbase.client.Delete;
|
||||||
|
import org.apache.hadoop.hbase.client.HBaseAdmin;
|
||||||
|
import org.apache.hadoop.hbase.client.HTable;
|
||||||
|
import org.apache.hadoop.hbase.client.Put;
|
||||||
import org.apache.hadoop.hbase.util.Bytes;
|
import org.apache.hadoop.hbase.util.Bytes;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.hbase.support;
|
package com.alibaba.otter.canal.client.adapter.hbase.support;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import java.sql.Time;
|
import java.sql.Time;
|
||||||
@@ -13,81 +16,44 @@ import java.util.Date;
|
|||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public enum PhType {
|
public enum PhType {
|
||||||
DEFAULT(-1, "VARCHAR"),
|
DEFAULT, UNSIGNED_INT, UNSIGNED_LONG, UNSIGNED_TINYINT, UNSIGNED_SMALLINT, UNSIGNED_FLOAT,
|
||||||
UNSIGNED_INT(4, "UNSIGNED_INT"),
|
UNSIGNED_DOUBLE, INTEGER, BIGINT, TINYINT, SMALLINT, FLOAT, DOUBLE, DECIMAL, BOOLEAN, UNSIGNED_TIME,
|
||||||
UNSIGNED_LONG(8, "UNSIGNED_LONG"),
|
UNSIGNED_DATE, UNSIGNED_TIMESTAMP, TIME, DATE, TIMESTAMP, VARCHAR, VARBINARY;
|
||||||
UNSIGNED_TINYINT(1, "UNSIGNED_TINYINT"),
|
|
||||||
UNSIGNED_SMALLINT(2, "UNSIGNED_SMALLINT"),
|
|
||||||
UNSIGNED_FLOAT(4, "UNSIGNED_FLOAT"),
|
|
||||||
UNSIGNED_DOUBLE(8, "UNSIGNED_DOUBLE"),
|
|
||||||
INTEGER(4, "INTEGER"),
|
|
||||||
BIGINT(8, "BIGINT"),
|
|
||||||
TINYINT(1, "TINYINT"),
|
|
||||||
SMALLINT(2, "SMALLINT"),
|
|
||||||
FLOAT(4, "FLOAT"),
|
|
||||||
DOUBLE(8, "DOUBLE"),
|
|
||||||
DECIMAL(-1, "DECIMAL"),
|
|
||||||
BOOLEAN(1, "BOOLEAN"),
|
|
||||||
UNSIGNED_TIME(8, "UNSIGNED_TIME"),
|
|
||||||
UNSIGNED_DATE(8, "UNSIGNED_DATE"),
|
|
||||||
UNSIGNED_TIMESTAMP(12, "UNSIGNED_TIMESTAMP"),
|
|
||||||
TIME(8, "TIME"),
|
|
||||||
DATE(8, "DATE"),
|
|
||||||
TIMESTAMP(12, "TIMESTAMP"),
|
|
||||||
VARCHAR(-1, "VARCHAR"),
|
|
||||||
VARBINARY(-1, "VARBINARY");
|
|
||||||
|
|
||||||
/**
|
private static Logger logger = LoggerFactory.getLogger(PhType.class);
|
||||||
* -1:长度可变
|
|
||||||
*/
|
|
||||||
private int len;
|
|
||||||
private String type;
|
|
||||||
|
|
||||||
PhType(int len, String type) {
|
|
||||||
this.len = len;
|
|
||||||
this.type = type;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getLen() {
|
|
||||||
return len;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getType() {
|
|
||||||
return this.type;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static PhType getType(Class<?> javaType) {
|
public static PhType getType(Class<?> javaType) {
|
||||||
if (javaType == null) return DEFAULT;
|
if (javaType == null) return DEFAULT;
|
||||||
PhType phType;
|
PhType phType;
|
||||||
if (Integer.class.isAssignableFrom(javaType) || int.class.isAssignableFrom(javaType)) {
|
if (Integer.class == javaType || int.class == javaType) {
|
||||||
phType = INTEGER;
|
phType = INTEGER;
|
||||||
} else if (Long.class.isAssignableFrom(javaType) || long.class.isAssignableFrom(javaType)) {
|
} else if (Long.class == javaType || long.class == javaType) {
|
||||||
phType = BIGINT;
|
phType = BIGINT;
|
||||||
} else if (Byte.class.isAssignableFrom(javaType) || byte.class.isAssignableFrom(javaType)) {
|
} else if (Byte.class == javaType || byte.class == javaType) {
|
||||||
phType = TINYINT;
|
phType = TINYINT;
|
||||||
} else if (Short.class.isAssignableFrom(javaType) || short.class.isAssignableFrom(javaType)) {
|
} else if (Short.class == javaType || short.class == javaType) {
|
||||||
phType = SMALLINT;
|
phType = SMALLINT;
|
||||||
} else if (Float.class.isAssignableFrom(javaType) || float.class.isAssignableFrom(javaType)) {
|
} else if (Float.class == javaType || float.class == javaType) {
|
||||||
phType = FLOAT;
|
phType = FLOAT;
|
||||||
} else if (Double.class.isAssignableFrom(javaType) || double.class.isAssignableFrom(javaType)) {
|
} else if (Double.class == javaType || double.class == javaType) {
|
||||||
phType = DOUBLE;
|
phType = DOUBLE;
|
||||||
} else if (Boolean.class.isAssignableFrom(javaType) || boolean.class.isAssignableFrom(javaType)) {
|
} else if (Boolean.class == javaType || boolean.class == javaType) {
|
||||||
phType = BOOLEAN;
|
phType = BOOLEAN;
|
||||||
} else if (java.sql.Date.class.isAssignableFrom(javaType)) {
|
} else if (java.sql.Date.class == javaType) {
|
||||||
phType = DATE;
|
phType = DATE;
|
||||||
} else if (Time.class.isAssignableFrom(javaType)) {
|
} else if (Time.class == javaType) {
|
||||||
phType = DATE;
|
phType = DATE;
|
||||||
} else if (Timestamp.class.isAssignableFrom(javaType)) {
|
} else if (Timestamp.class == javaType) {
|
||||||
phType = TIMESTAMP;
|
phType = TIMESTAMP;
|
||||||
} else if (Date.class.isAssignableFrom(javaType)) {
|
} else if (Date.class == javaType) {
|
||||||
phType = DATE;
|
phType = DATE;
|
||||||
} else if (byte[].class.isAssignableFrom(javaType)) {
|
} else if (byte[].class == javaType) {
|
||||||
phType = VARBINARY;
|
phType = VARBINARY;
|
||||||
} else if (String.class.isAssignableFrom(javaType)) {
|
} else if (String.class == javaType) {
|
||||||
phType = VARCHAR;
|
phType = VARCHAR;
|
||||||
} else if (BigDecimal.class.isAssignableFrom(javaType)) {
|
} else if (BigDecimal.class == javaType) {
|
||||||
phType = DECIMAL;
|
phType = DECIMAL;
|
||||||
} else if (BigInteger.class.isAssignableFrom(javaType)) {
|
} else if (BigInteger.class == javaType) {
|
||||||
phType = UNSIGNED_LONG;
|
phType = UNSIGNED_LONG;
|
||||||
} else {
|
} else {
|
||||||
phType = DEFAULT;
|
phType = DEFAULT;
|
||||||
@@ -97,54 +63,11 @@ public enum PhType {
|
|||||||
|
|
||||||
public static PhType getType(String type) {
|
public static PhType getType(String type) {
|
||||||
if (type == null) return DEFAULT;
|
if (type == null) return DEFAULT;
|
||||||
PhType phType;
|
try {
|
||||||
if (type.equalsIgnoreCase(UNSIGNED_INT.type)) {
|
return PhType.valueOf(type.toUpperCase());
|
||||||
phType = UNSIGNED_INT;
|
} catch (Exception e) {
|
||||||
} else if (type.equalsIgnoreCase(UNSIGNED_LONG.type)) {
|
logger.error(e.getMessage(), e);
|
||||||
phType = UNSIGNED_LONG;
|
return DEFAULT;
|
||||||
} else if (type.equalsIgnoreCase(UNSIGNED_TINYINT.type)) {
|
}
|
||||||
phType = UNSIGNED_TINYINT;
|
|
||||||
} else if (type.equalsIgnoreCase(UNSIGNED_SMALLINT.type)) {
|
|
||||||
phType = UNSIGNED_SMALLINT;
|
|
||||||
} else if (type.equalsIgnoreCase(UNSIGNED_FLOAT.type)) {
|
|
||||||
phType = UNSIGNED_FLOAT;
|
|
||||||
} else if (type.equalsIgnoreCase(UNSIGNED_DOUBLE.type)) {
|
|
||||||
phType = UNSIGNED_DOUBLE;
|
|
||||||
} else if (type.equalsIgnoreCase(INTEGER.type)) {
|
|
||||||
phType = INTEGER;
|
|
||||||
} else if (type.equalsIgnoreCase(BIGINT.type)) {
|
|
||||||
phType = BIGINT;
|
|
||||||
} else if (type.equalsIgnoreCase(TINYINT.type)) {
|
|
||||||
phType = TINYINT;
|
|
||||||
} else if (type.equalsIgnoreCase(SMALLINT.type)) {
|
|
||||||
phType = SMALLINT;
|
|
||||||
} else if (type.equalsIgnoreCase(FLOAT.type)) {
|
|
||||||
phType = FLOAT;
|
|
||||||
} else if (type.equalsIgnoreCase(DOUBLE.type)) {
|
|
||||||
phType = DOUBLE;
|
|
||||||
} else if (type.equalsIgnoreCase(BOOLEAN.type)) {
|
|
||||||
phType = BOOLEAN;
|
|
||||||
} else if (type.equalsIgnoreCase(UNSIGNED_TIME.type)) {
|
|
||||||
phType = UNSIGNED_TIME;
|
|
||||||
} else if (type.equalsIgnoreCase(UNSIGNED_DATE.type)) {
|
|
||||||
phType = UNSIGNED_DATE;
|
|
||||||
} else if (type.equalsIgnoreCase(UNSIGNED_TIMESTAMP.type)) {
|
|
||||||
phType = UNSIGNED_TIMESTAMP;
|
|
||||||
} else if (type.equalsIgnoreCase(TIME.type)) {
|
|
||||||
phType = TIME;
|
|
||||||
} else if (type.equalsIgnoreCase(DATE.type)) {
|
|
||||||
phType = DATE;
|
|
||||||
} else if (type.equalsIgnoreCase(TIMESTAMP.type)) {
|
|
||||||
phType = TIMESTAMP;
|
|
||||||
} else if (type.equalsIgnoreCase(VARCHAR.type)) {
|
|
||||||
phType = VARCHAR;
|
|
||||||
} else if (type.equalsIgnoreCase(VARBINARY.type)) {
|
|
||||||
phType = VARBINARY;
|
|
||||||
} else if (type.equalsIgnoreCase(DECIMAL.type)) {
|
|
||||||
phType = DECIMAL;
|
|
||||||
} else {
|
|
||||||
phType = DEFAULT;
|
|
||||||
}
|
|
||||||
return phType;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -169,7 +169,8 @@ public class PhTypeUtil {
|
|||||||
|
|
||||||
private static int encodeInt(int v, byte[] b, int o) {
|
private static int encodeInt(int v, byte[] b, int o) {
|
||||||
checkForSufficientLength(b, o, Bytes.SIZEOF_INT);
|
checkForSufficientLength(b, o, Bytes.SIZEOF_INT);
|
||||||
b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER is binary comparable
|
b[o + 0] = (byte) ((v >> 24) ^ 0x80); // Flip sign bit so that INTEGER
|
||||||
|
// is binary comparable
|
||||||
b[o + 1] = (byte) (v >> 16);
|
b[o + 1] = (byte) (v >> 16);
|
||||||
b[o + 2] = (byte) (v >> 8);
|
b[o + 2] = (byte) (v >> 8);
|
||||||
b[o + 3] = (byte) v;
|
b[o + 3] = (byte) v;
|
||||||
@@ -209,7 +210,8 @@ public class PhTypeUtil {
|
|||||||
|
|
||||||
private static int encodeLong(long v, byte[] b, int o) {
|
private static int encodeLong(long v, byte[] b, int o) {
|
||||||
checkForSufficientLength(b, o, Bytes.SIZEOF_LONG);
|
checkForSufficientLength(b, o, Bytes.SIZEOF_LONG);
|
||||||
b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER is binary comparable
|
b[o + 0] = (byte) ((v >> 56) ^ 0x80); // Flip sign bit so that INTEGER
|
||||||
|
// is binary comparable
|
||||||
b[o + 1] = (byte) (v >> 48);
|
b[o + 1] = (byte) (v >> 48);
|
||||||
b[o + 2] = (byte) (v >> 40);
|
b[o + 2] = (byte) (v >> 40);
|
||||||
b[o + 3] = (byte) (v >> 32);
|
b[o + 3] = (byte) (v >> 32);
|
||||||
@@ -255,7 +257,8 @@ public class PhTypeUtil {
|
|||||||
|
|
||||||
private static int encodeShort(short v, byte[] b, int o) {
|
private static int encodeShort(short v, byte[] b, int o) {
|
||||||
checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT);
|
checkForSufficientLength(b, o, Bytes.SIZEOF_SHORT);
|
||||||
b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is binary comparable
|
b[o + 0] = (byte) ((v >> 8) ^ 0x80); // Flip sign bit so that Short is
|
||||||
|
// binary comparable
|
||||||
b[o + 1] = (byte) v;
|
b[o + 1] = (byte) v;
|
||||||
return Bytes.SIZEOF_SHORT;
|
return Bytes.SIZEOF_SHORT;
|
||||||
}
|
}
|
||||||
@@ -287,7 +290,8 @@ public class PhTypeUtil {
|
|||||||
|
|
||||||
private static int encodeByte(byte v, byte[] b, int o) {
|
private static int encodeByte(byte v, byte[] b, int o) {
|
||||||
checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);
|
checkForSufficientLength(b, o, Bytes.SIZEOF_BYTE);
|
||||||
b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary comparable
|
b[o] = (byte) (v ^ 0x80); // Flip sign bit so that Short is binary
|
||||||
|
// comparable
|
||||||
return Bytes.SIZEOF_BYTE;
|
return Bytes.SIZEOF_BYTE;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -546,7 +550,8 @@ public class PhTypeUtil {
|
|||||||
multiplyBy = 10;
|
multiplyBy = 10;
|
||||||
divideBy = BigInteger.TEN;
|
divideBy = BigInteger.TEN;
|
||||||
}
|
}
|
||||||
// Normalize the scale based on what is necessary to end up with a base 100
|
// Normalize the scale based on what is necessary to end up with a base
|
||||||
|
// 100
|
||||||
// decimal (i.e. 10.123e3)
|
// decimal (i.e. 10.123e3)
|
||||||
int digitOffset;
|
int digitOffset;
|
||||||
BigInteger compareAgainst;
|
BigInteger compareAgainst;
|
||||||
@@ -564,7 +569,8 @@ public class PhTypeUtil {
|
|||||||
if (length <= MAX_BIG_DECIMAL_BYTES) {
|
if (length <= MAX_BIG_DECIMAL_BYTES) {
|
||||||
result[--index] = NEG_TERMINAL_BYTE;
|
result[--index] = NEG_TERMINAL_BYTE;
|
||||||
} else {
|
} else {
|
||||||
// Adjust length and offset down because we don't have enough room
|
// Adjust length and offset down because we don't have enough
|
||||||
|
// room
|
||||||
length = MAX_BIG_DECIMAL_BYTES;
|
length = MAX_BIG_DECIMAL_BYTES;
|
||||||
index = offset + length;
|
index = offset + length;
|
||||||
}
|
}
|
||||||
@@ -593,8 +599,8 @@ public class PhTypeUtil {
|
|||||||
|
|
||||||
private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) {
|
private static void checkForSufficientLength(byte[] b, int offset, int requiredLength) {
|
||||||
if (b.length < offset + requiredLength) {
|
if (b.length < offset + requiredLength) {
|
||||||
throw new RuntimeException(
|
throw new RuntimeException("Expected length of at least " + requiredLength + " bytes, but had "
|
||||||
"Expected length of at least " + requiredLength + " bytes, but had " + (b.length - offset));
|
+ (b.length - offset));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.hbase.support;
|
package com.alibaba.otter.canal.client.adapter.hbase.support;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.BigInteger;
|
import java.math.BigInteger;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
@@ -11,60 +14,20 @@ import java.util.Date;
|
|||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public enum Type {
|
public enum Type {
|
||||||
DEFAULT("STRING"),
|
DEFAULT, STRING, INTEGER, LONG, SHORT, BOOLEAN, FLOAT, DOUBLE, BIGDECIMAL, DATE, BYTE, BYTES;
|
||||||
STRING("STRING"),
|
|
||||||
INTEGER("INTEGER"),
|
|
||||||
LONG("LONG"),
|
|
||||||
SHORT("SHORT"),
|
|
||||||
BOOLEAN("BOOLEAN"),
|
|
||||||
FLOAT("FLOAT"),
|
|
||||||
DOUBLE("DOUBLE"),
|
|
||||||
BIGDECIMAL("BIGDECIMAL"),
|
|
||||||
DATE("DATE"),
|
|
||||||
BYTE("BYTE"),
|
|
||||||
BYTES("BYTES");
|
|
||||||
|
|
||||||
private String type;
|
private static Logger logger = LoggerFactory.getLogger(Type.class);
|
||||||
|
|
||||||
Type(String type) {
|
|
||||||
this.type = type;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getType() {
|
|
||||||
return type;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Type getType(String type) {
|
public static Type getType(String type) {
|
||||||
if (type == null) {
|
if (type == null) {
|
||||||
return DEFAULT;
|
return DEFAULT;
|
||||||
}
|
}
|
||||||
Type res;
|
try {
|
||||||
if (type.equalsIgnoreCase("STRING")) {
|
return Type.valueOf(type);
|
||||||
res = STRING;
|
} catch (Exception e) {
|
||||||
} else if (type.equalsIgnoreCase("INTEGER")) {
|
logger.error(e.getMessage(), e);
|
||||||
res = INTEGER;
|
return DEFAULT;
|
||||||
} else if (type.equalsIgnoreCase("LONG")) {
|
|
||||||
res = LONG;
|
|
||||||
} else if (type.equalsIgnoreCase("SHORT")) {
|
|
||||||
res = SHORT;
|
|
||||||
} else if (type.equalsIgnoreCase("BOOLEAN")) {
|
|
||||||
res = BOOLEAN;
|
|
||||||
} else if (type.equalsIgnoreCase("FLOAT")) {
|
|
||||||
res = FLOAT;
|
|
||||||
} else if (type.equalsIgnoreCase("DOUBLE")) {
|
|
||||||
res = DOUBLE;
|
|
||||||
} else if (type.equalsIgnoreCase("BIGDECIMAL")) {
|
|
||||||
res = BIGDECIMAL;
|
|
||||||
} else if (type.equalsIgnoreCase("DATE")) {
|
|
||||||
res = DATE;
|
|
||||||
} else if (type.equalsIgnoreCase("BYTE")) {
|
|
||||||
res = BYTE;
|
|
||||||
} else if (type.equalsIgnoreCase("BYTES")) {
|
|
||||||
res = BYTES;
|
|
||||||
} else {
|
|
||||||
res = DEFAULT;
|
|
||||||
}
|
}
|
||||||
return res;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Type getType(Class<?> javaType) {
|
public static Type getType(Class<?> javaType) {
|
||||||
@@ -72,29 +35,29 @@ public enum Type {
|
|||||||
return DEFAULT;
|
return DEFAULT;
|
||||||
}
|
}
|
||||||
Type type;
|
Type type;
|
||||||
if (Integer.class.isAssignableFrom(javaType) || int.class.isAssignableFrom(javaType)) {
|
if (Integer.class == javaType || int.class == javaType) {
|
||||||
type = INTEGER;
|
type = INTEGER;
|
||||||
} else if (Long.class.isAssignableFrom(javaType) || long.class.isAssignableFrom(javaType)) {
|
} else if (Long.class == javaType || long.class == javaType) {
|
||||||
type = LONG;
|
type = LONG;
|
||||||
} else if (Byte.class.isAssignableFrom(javaType) || byte.class.isAssignableFrom(javaType)) {
|
} else if (Byte.class == javaType || byte.class == javaType) {
|
||||||
type = BYTE;
|
type = BYTE;
|
||||||
} else if (Short.class.isAssignableFrom(javaType) || short.class.isAssignableFrom(javaType)) {
|
} else if (Short.class == javaType || short.class == javaType) {
|
||||||
type = SHORT;
|
type = SHORT;
|
||||||
} else if (Float.class.isAssignableFrom(javaType) || float.class.isAssignableFrom(javaType)) {
|
} else if (Float.class == javaType || float.class == javaType) {
|
||||||
type = FLOAT;
|
type = FLOAT;
|
||||||
} else if (Double.class.isAssignableFrom(javaType) || double.class.isAssignableFrom(javaType)) {
|
} else if (Double.class == javaType || double.class == javaType) {
|
||||||
type = DOUBLE;
|
type = DOUBLE;
|
||||||
} else if (Boolean.class.isAssignableFrom(javaType) || boolean.class.isAssignableFrom(javaType)) {
|
} else if (Boolean.class == javaType || boolean.class == javaType) {
|
||||||
type = BOOLEAN;
|
type = BOOLEAN;
|
||||||
} else if (Date.class.isAssignableFrom(javaType)) {
|
} else if (Date.class == javaType) {
|
||||||
type = DATE;
|
type = DATE;
|
||||||
} else if (byte[].class.isAssignableFrom(javaType)) {
|
} else if (byte[].class == javaType) {
|
||||||
type = BYTES;
|
type = BYTES;
|
||||||
} else if (String.class.isAssignableFrom(javaType)) {
|
} else if (String.class == javaType) {
|
||||||
type = STRING;
|
type = STRING;
|
||||||
} else if (BigDecimal.class.isAssignableFrom(javaType)) {
|
} else if (BigDecimal.class == javaType) {
|
||||||
type = BIGDECIMAL;
|
type = BIGDECIMAL;
|
||||||
} else if (BigInteger.class.isAssignableFrom(javaType)) {
|
} else if (BigInteger.class == javaType) {
|
||||||
type = LONG;
|
type = LONG;
|
||||||
} else {
|
} else {
|
||||||
type = DEFAULT;
|
type = DEFAULT;
|
||||||
|
|||||||
@@ -21,29 +21,30 @@ public class TypeUtil {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
byte[] bytes;
|
byte[] bytes;
|
||||||
if (obj instanceof String) {
|
Class<?> clazz = obj.getClass();
|
||||||
|
if (clazz == String.class) {
|
||||||
bytes = Bytes.toBytes((String) obj);
|
bytes = Bytes.toBytes((String) obj);
|
||||||
} else if (obj instanceof Integer) {
|
} else if (clazz == Integer.class || clazz == int.class) {
|
||||||
bytes = Bytes.toBytes((Integer) obj);
|
bytes = Bytes.toBytes((Integer) obj);
|
||||||
} else if (obj instanceof Long) {
|
} else if (clazz == Long.class || clazz == long.class) {
|
||||||
bytes = Bytes.toBytes((Long) obj);
|
bytes = Bytes.toBytes((Long) obj);
|
||||||
} else if (obj instanceof Short) {
|
} else if (clazz == Short.class || clazz == short.class) {
|
||||||
bytes = Bytes.toBytes((Short) obj);
|
bytes = Bytes.toBytes((Short) obj);
|
||||||
} else if (obj instanceof Boolean) {
|
} else if (clazz == Boolean.class || clazz == boolean.class) {
|
||||||
bytes = Bytes.toBytes((Boolean) obj);
|
bytes = Bytes.toBytes((Boolean) obj);
|
||||||
} else if (obj instanceof Float) {
|
} else if (clazz == Float.class || clazz == float.class) {
|
||||||
bytes = Bytes.toBytes((Float) obj);
|
bytes = Bytes.toBytes((Float) obj);
|
||||||
} else if (obj instanceof Double) {
|
} else if (clazz == Double.class || clazz == double.class) {
|
||||||
bytes = Bytes.toBytes((Double) obj);
|
bytes = Bytes.toBytes((Double) obj);
|
||||||
} else if (obj instanceof BigDecimal) {
|
} else if (clazz == Byte.class || clazz == byte.class) {
|
||||||
bytes = Bytes.toBytes((BigDecimal) obj);
|
|
||||||
} else if (obj instanceof BigInteger) {
|
|
||||||
bytes = Bytes.toBytes(((BigInteger) obj).longValue());
|
|
||||||
} else if (obj instanceof Date) {
|
|
||||||
bytes = Bytes.toBytes(((Date) obj).getTime());
|
|
||||||
} else if (obj instanceof Byte) {
|
|
||||||
bytes = new byte[] { (byte) obj };
|
bytes = new byte[] { (byte) obj };
|
||||||
} else if (obj instanceof byte[]) {
|
} else if (clazz == BigDecimal.class) {
|
||||||
|
bytes = Bytes.toBytes((BigDecimal) obj);
|
||||||
|
} else if (clazz == BigInteger.class) {
|
||||||
|
bytes = Bytes.toBytes(((BigInteger) obj).longValue());
|
||||||
|
} else if (clazz == Date.class) {
|
||||||
|
bytes = Bytes.toBytes(((Date) obj).getTime());
|
||||||
|
} else if (clazz == byte[].class) {
|
||||||
bytes = (byte[]) obj;
|
bytes = (byte[]) obj;
|
||||||
} else {
|
} else {
|
||||||
// 其余类型统一转换为string
|
// 其余类型统一转换为string
|
||||||
@@ -92,50 +93,51 @@ public class TypeUtil {
|
|||||||
return b;
|
return b;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
public static <T> T toObject(byte[] bytes, Class<T> clazz) {
|
public static <T> T toObject(byte[] bytes, Class<T> clazz) {
|
||||||
if (bytes == null) {
|
if (bytes == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
Object res;
|
Object res;
|
||||||
if (String.class.isAssignableFrom(clazz)) {
|
if (String.class == clazz) {
|
||||||
res = Bytes.toString(bytes);
|
res = Bytes.toString(bytes);
|
||||||
} else if (Integer.class.isAssignableFrom(clazz)) {
|
} else if (Integer.class == clazz || int.class == clazz) {
|
||||||
res = Bytes.toInt(bytes);
|
res = Bytes.toInt(bytes);
|
||||||
} else if (Long.class.isAssignableFrom(clazz)) {
|
} else if (Long.class == clazz || long.class == clazz) {
|
||||||
res = Bytes.toLong(bytes);
|
res = Bytes.toLong(bytes);
|
||||||
} else if (Short.class.isAssignableFrom(clazz)) {
|
} else if (Short.class == clazz || short.class == clazz) {
|
||||||
res = Bytes.toShort(bytes);
|
res = Bytes.toShort(bytes);
|
||||||
} else if (Boolean.class.isAssignableFrom(clazz)) {
|
} else if (Boolean.class == clazz || boolean.class == clazz) {
|
||||||
res = Bytes.toBoolean(bytes);
|
res = Bytes.toBoolean(bytes);
|
||||||
} else if (Float.class.isAssignableFrom(clazz)) {
|
} else if (Float.class == clazz || float.class == clazz) {
|
||||||
res = Bytes.toFloat(bytes);
|
res = Bytes.toFloat(bytes);
|
||||||
} else if (Double.class.isAssignableFrom(clazz)) {
|
} else if (Double.class == clazz || double.class == clazz) {
|
||||||
res = Bytes.toDouble(bytes);
|
res = Bytes.toDouble(bytes);
|
||||||
} else if (BigDecimal.class.isAssignableFrom(clazz)) {
|
} else if (Byte.class == clazz || byte.class == clazz) {
|
||||||
|
res = bytes[0];
|
||||||
|
} else if (BigDecimal.class == clazz) {
|
||||||
res = Bytes.toBigDecimal(bytes);
|
res = Bytes.toBigDecimal(bytes);
|
||||||
} else if (BigInteger.class.isAssignableFrom(clazz)) {
|
} else if (BigInteger.class == clazz) {
|
||||||
res = Bytes.toLong(bytes);
|
res = Bytes.toLong(bytes);
|
||||||
} else if (java.sql.Date.class.isAssignableFrom(clazz)) {
|
} else if (java.sql.Date.class == clazz) {
|
||||||
long ts = Bytes.toLong(bytes);
|
long ts = Bytes.toLong(bytes);
|
||||||
res = new java.sql.Date(ts);
|
res = new java.sql.Date(ts);
|
||||||
} else if (Time.class.isAssignableFrom(clazz)) {
|
} else if (Time.class == clazz) {
|
||||||
long ts = Bytes.toLong(bytes);
|
long ts = Bytes.toLong(bytes);
|
||||||
res = new Time(ts);
|
res = new Time(ts);
|
||||||
} else if (Timestamp.class.isAssignableFrom(clazz)) {
|
} else if (Timestamp.class == clazz) {
|
||||||
long ts = Bytes.toLong(bytes);
|
long ts = Bytes.toLong(bytes);
|
||||||
res = new Timestamp(ts);
|
res = new Timestamp(ts);
|
||||||
} else if (Date.class.isAssignableFrom(clazz)) {
|
} else if (Date.class == clazz) {
|
||||||
long ts = Bytes.toLong(bytes);
|
long ts = Bytes.toLong(bytes);
|
||||||
res = new Date(ts);
|
res = new Date(ts);
|
||||||
} else if (Byte.class.isAssignableFrom(clazz)) {
|
|
||||||
res = bytes[0];
|
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalArgumentException("mismatch class type");
|
throw new IllegalArgumentException("mismatch class type");
|
||||||
}
|
}
|
||||||
// noinspection unchecked
|
|
||||||
return (T) res;
|
return (T) res;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
public static <T> T toObject(byte[] bytes, Type type) {
|
public static <T> T toObject(byte[] bytes, Type type) {
|
||||||
if (bytes == null) {
|
if (bytes == null) {
|
||||||
return null;
|
return null;
|
||||||
@@ -182,7 +184,6 @@ public class TypeUtil {
|
|||||||
} else {
|
} else {
|
||||||
throw new IllegalArgumentException("mismatch class type");
|
throw new IllegalArgumentException("mismatch class type");
|
||||||
}
|
}
|
||||||
// noinspection unchecked
|
|
||||||
return (T) res;
|
return (T) res;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
# 详细映射配置
|
|
||||||
mytest_person2.yml
|
|
||||||
|
|
||||||
# 简易配置, 只用指定数据库名.表名, 详细配置全部使用默认
|
|
||||||
mytest.person
|
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
hbaseOrm:
|
dataSourceKey: defaultDS
|
||||||
|
hbaseMapping:
|
||||||
mode: PHOENIX #NATIVE #STRING
|
mode: PHOENIX #NATIVE #STRING
|
||||||
|
destination: example
|
||||||
database: mytest # 数据库名
|
database: mytest # 数据库名
|
||||||
table: person2 # 数据库表名
|
table: person2 # 数据库表名
|
||||||
hbaseTable: MYTEST.PERSON2 # HBase表名
|
hbaseTable: MYTEST.PERSON2 # HBase表名
|
||||||
@@ -15,6 +17,8 @@ hbaseOrm:
|
|||||||
type: $DECIMAL
|
type: $DECIMAL
|
||||||
c_time: C_TIME$UNSIGNED_TIMESTAMP
|
c_time: C_TIME$UNSIGNED_TIMESTAMP
|
||||||
birthday: BIRTHDAY$DATE
|
birthday: BIRTHDAY$DATE
|
||||||
|
excludeColumns:
|
||||||
|
- lat # 忽略字段
|
||||||
|
|
||||||
# -- NATIVE类型
|
# -- NATIVE类型
|
||||||
# $DEFAULT
|
# $DEFAULT
|
||||||
@@ -43,7 +47,7 @@ hbaseOrm:
|
|||||||
# $TINYINT 对应PHOENIX里的TINYINT 1字节
|
# $TINYINT 对应PHOENIX里的TINYINT 1字节
|
||||||
# $SMALLINT 对应PHOENIX里的SMALLINT 2字节
|
# $SMALLINT 对应PHOENIX里的SMALLINT 2字节
|
||||||
# $FLOAT 对应PHOENIX里的FLOAT 4字节
|
# $FLOAT 对应PHOENIX里的FLOAT 4字节
|
||||||
# DOUBLE 对应PHOENIX里的DOUBLE 8字节
|
# $DOUBLE 对应PHOENIX里的DOUBLE 8字节
|
||||||
# $BOOLEAN 对应PHOENIX里的BOOLEAN 1字节
|
# $BOOLEAN 对应PHOENIX里的BOOLEAN 1字节
|
||||||
# $TIME 对应PHOENIX里的TIME 8字节
|
# $TIME 对应PHOENIX里的TIME 8字节
|
||||||
# $DATE 对应PHOENIX里的DATE 8字节
|
# $DATE 对应PHOENIX里的DATE 8字节
|
||||||
207
client-adapter/launcher/pom.xml
Normal file
207
client-adapter/launcher/pom.xml
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<parent>
|
||||||
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
<version>1.1.1</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
<artifactId>client-adapter.launcher</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<name>canal client adapter launcher module for otter ${project.version}</name>
|
||||||
|
|
||||||
|
<dependencyManagement>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-dependencies</artifactId>
|
||||||
|
<version>2.0.1.RELEASE</version>
|
||||||
|
<type>pom</type>
|
||||||
|
<scope>import</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</dependencyManagement>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
<artifactId>client-adapter.common</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
<artifactId>canal.client</artifactId>
|
||||||
|
<version>1.1.1</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.yaml</groupId>
|
||||||
|
<artifactId>snakeyaml</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.curator</groupId>
|
||||||
|
<artifactId>curator-recipes</artifactId>
|
||||||
|
<version>2.10.0</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- 单独引入rocketmq依赖 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.rocketmq</groupId>
|
||||||
|
<artifactId>rocketmq-client</artifactId>
|
||||||
|
<version>4.3.0</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- 单独引入kafka依赖 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.kafka</groupId>
|
||||||
|
<artifactId>kafka-clients</artifactId>
|
||||||
|
<version>1.1.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- outer adapter jar with dependencies-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
<artifactId>client-adapter.logger</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>*</artifactId>
|
||||||
|
<groupId>*</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
<classifier>jar-with-dependencies</classifier>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
<artifactId>client-adapter.hbase</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<artifactId>*</artifactId>
|
||||||
|
<groupId>*</groupId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
|
<classifier>jar-with-dependencies</classifier>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>canal-adapter-launcher</finalName>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
|
<version>2.0.1.RELEASE</version>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>
|
||||||
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
<artifactId>client-adapter.hbase</artifactId>
|
||||||
|
</exclude>
|
||||||
|
<exclude>
|
||||||
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
<artifactId>client-adapter.logger</artifactId>
|
||||||
|
</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>repackage</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-antrun-plugin</artifactId>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>run</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<tasks>
|
||||||
|
<copy todir="${project.basedir}/target/config" overwrite="true">
|
||||||
|
<fileset dir="${project.basedir}/src/main/resources" erroronmissingdir="true">
|
||||||
|
<include name="*.yml" />
|
||||||
|
</fileset>
|
||||||
|
</copy>
|
||||||
|
<copy todir="${project.basedir}/target/config/hbase" overwrite="true">
|
||||||
|
<fileset dir="${project.basedir}/../hbase/src/main/resources/hbase" erroronmissingdir="true">
|
||||||
|
<include name="*.yml" />
|
||||||
|
</fileset>
|
||||||
|
</copy>
|
||||||
|
</tasks>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-dependency-plugin</artifactId>
|
||||||
|
<version>2.10</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>copy-dependencies-to-canal-client-service</id>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>copy-dependencies</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<includeClassifiers>jar-with-dependencies</includeClassifiers>
|
||||||
|
<outputDirectory>${project.basedir}/target/lib</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<profiles>
|
||||||
|
<profile>
|
||||||
|
<id>release</id>
|
||||||
|
<activation>
|
||||||
|
<property>
|
||||||
|
<name>env</name>
|
||||||
|
<value>release</value>
|
||||||
|
</property>
|
||||||
|
</activation>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<appendAssemblyId>false</appendAssemblyId>
|
||||||
|
<descriptors>
|
||||||
|
<descriptor>${basedir}/src/main/assembly/release.xml</descriptor>
|
||||||
|
</descriptors>
|
||||||
|
<finalName>${project.artifactId}-${project.version}</finalName>
|
||||||
|
<outputDirectory>${project.basedir}/../../target</outputDirectory>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>make-assembly</id>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>single</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</profile>
|
||||||
|
</profiles>
|
||||||
|
</project>
|
||||||
34
client-adapter/launcher/src/main/assembly/release.xml
Normal file
34
client-adapter/launcher/src/main/assembly/release.xml
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
|
||||||
|
<id>canal-adapter</id>
|
||||||
|
<formats>
|
||||||
|
<format>tar.gz</format>
|
||||||
|
</formats>
|
||||||
|
<fileSets>
|
||||||
|
<fileSet>
|
||||||
|
<directory>${project.build.directory}</directory>
|
||||||
|
<outputDirectory>/</outputDirectory>
|
||||||
|
<includes>
|
||||||
|
<include>*.jar</include>
|
||||||
|
</includes>
|
||||||
|
</fileSet>
|
||||||
|
|
||||||
|
<fileSet>
|
||||||
|
<directory>${project.build.directory}/lib</directory>
|
||||||
|
<outputDirectory>/lib/</outputDirectory>
|
||||||
|
<includes>
|
||||||
|
<include>*.jar</include>
|
||||||
|
</includes>
|
||||||
|
</fileSet>
|
||||||
|
|
||||||
|
<fileSet>
|
||||||
|
<directory>${project.build.directory}/config</directory>
|
||||||
|
<outputDirectory>/config/</outputDirectory>
|
||||||
|
<includes>
|
||||||
|
<include>**</include>
|
||||||
|
</includes>
|
||||||
|
</fileSet>
|
||||||
|
</fileSets>
|
||||||
|
<baseDirectory>/</baseDirectory>
|
||||||
|
</assembly>
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 启动入口
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@SpringBootApplication
|
||||||
|
public class CanalAdapterApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
new SpringApplicationBuilder(CanalAdapterApplication.class).run(args);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.common;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
|
||||||
|
import org.apache.curator.framework.CuratorFramework;
|
||||||
|
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.config.CuratorClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Etl 同步锁
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class EtlLock {
|
||||||
|
|
||||||
|
private static final Map<String, ReentrantLock> LOCAL_LOCK = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private static final Map<String, InterProcessMutex> DISTRIBUTED_LOCK = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private static Mode mode = Mode.LOCAL;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private CuratorClient curatorClient;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
CuratorFramework curator = curatorClient.getCurator();
|
||||||
|
if (curator != null) {
|
||||||
|
mode = Mode.DISTRIBUTED;
|
||||||
|
} else {
|
||||||
|
mode = Mode.LOCAL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ReentrantLock getLock(String key) {
|
||||||
|
ReentrantLock lock = LOCAL_LOCK.get(key);
|
||||||
|
if (lock == null) {
|
||||||
|
synchronized (EtlLock.class) {
|
||||||
|
lock = LOCAL_LOCK.get(key);
|
||||||
|
if (lock == null) {
|
||||||
|
lock = new ReentrantLock();
|
||||||
|
LOCAL_LOCK.put(key, lock);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lock;
|
||||||
|
}
|
||||||
|
|
||||||
|
private InterProcessMutex getRemoteLock(String key) {
|
||||||
|
InterProcessMutex lock = DISTRIBUTED_LOCK.get(key);
|
||||||
|
if (lock == null) {
|
||||||
|
synchronized (EtlLock.class) {
|
||||||
|
lock = DISTRIBUTED_LOCK.get(key);
|
||||||
|
if (lock == null) {
|
||||||
|
lock = new InterProcessMutex(curatorClient.getCurator(), key);
|
||||||
|
DISTRIBUTED_LOCK.put(key, lock);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lock;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void lock(String key) throws Exception {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
getLock(key).lock();
|
||||||
|
} else {
|
||||||
|
InterProcessMutex lock = getRemoteLock(key);
|
||||||
|
lock.acquire();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean tryLock(String key, long timeout, TimeUnit unit) {
|
||||||
|
try {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
return getLock(key).tryLock(timeout, unit);
|
||||||
|
} else {
|
||||||
|
InterProcessMutex lock = getRemoteLock(key);
|
||||||
|
return lock.acquire(timeout, unit);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean tryLock(String key) {
|
||||||
|
try {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
return getLock(key).tryLock();
|
||||||
|
} else {
|
||||||
|
InterProcessMutex lock = getRemoteLock(key);
|
||||||
|
return lock.acquire(500, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unlock(String key) {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
getLock(key).unlock();
|
||||||
|
} else {
|
||||||
|
InterProcessMutex lock = getRemoteLock(key);
|
||||||
|
try {
|
||||||
|
lock.release();
|
||||||
|
} catch (Exception e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.common;
|
||||||
|
|
||||||
|
public enum Mode {
|
||||||
|
LOCAL, // 本地模式
|
||||||
|
DISTRIBUTED // 分布式
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.common;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
|
||||||
|
import org.apache.curator.framework.CuratorFramework;
|
||||||
|
import org.apache.curator.framework.recipes.cache.NodeCache;
|
||||||
|
import org.apache.zookeeper.CreateMode;
|
||||||
|
import org.apache.zookeeper.data.Stat;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.config.AdapterCanalConfig;
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.config.CuratorClient;
|
||||||
|
import com.alibaba.otter.canal.common.utils.BooleanMutex;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步开关
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class SyncSwitch {
|
||||||
|
|
||||||
|
private static final String SYN_SWITCH_ZK_NODE = "/sync-switch/";
|
||||||
|
|
||||||
|
private static final Map<String, BooleanMutex> LOCAL_LOCK = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private static final Map<String, BooleanMutex> DISTRIBUTED_LOCK = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private static Mode mode = Mode.LOCAL;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private AdapterCanalConfig adapterCanalConfig;
|
||||||
|
@Resource
|
||||||
|
private CuratorClient curatorClient;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
CuratorFramework curator = curatorClient.getCurator();
|
||||||
|
if (curator != null) {
|
||||||
|
mode = Mode.DISTRIBUTED;
|
||||||
|
DISTRIBUTED_LOCK.clear();
|
||||||
|
for (String destination : adapterCanalConfig.DESTINATIONS) {
|
||||||
|
// 对应每个destination注册锁
|
||||||
|
BooleanMutex mutex = new BooleanMutex(true);
|
||||||
|
initMutex(curator, destination, mutex);
|
||||||
|
DISTRIBUTED_LOCK.put(destination, mutex);
|
||||||
|
startListen(destination, mutex);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
mode = Mode.LOCAL;
|
||||||
|
LOCAL_LOCK.clear();
|
||||||
|
for (String destination : adapterCanalConfig.DESTINATIONS) {
|
||||||
|
// 对应每个destination注册锁
|
||||||
|
LOCAL_LOCK.put(destination, new BooleanMutex(true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void startListen(String destination, BooleanMutex mutex) {
|
||||||
|
try {
|
||||||
|
String path = SYN_SWITCH_ZK_NODE + destination;
|
||||||
|
CuratorFramework curator = curatorClient.getCurator();
|
||||||
|
final NodeCache nodeCache = new NodeCache(curator, path);
|
||||||
|
nodeCache.start();
|
||||||
|
nodeCache.getListenable().addListener(() -> initMutex(curator, destination, mutex));
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void initMutex(CuratorFramework curator, String destination, BooleanMutex mutex) {
|
||||||
|
try {
|
||||||
|
String path = SYN_SWITCH_ZK_NODE + destination;
|
||||||
|
Stat stat = curator.checkExists().forPath(path);
|
||||||
|
if (stat == null) {
|
||||||
|
if (!mutex.state()) {
|
||||||
|
mutex.set(true);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
String data = new String(curator.getData().forPath(path), StandardCharsets.UTF_8);
|
||||||
|
if ("on".equals(data)) {
|
||||||
|
if (!mutex.state()) {
|
||||||
|
mutex.set(true);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (mutex.state()) {
|
||||||
|
mutex.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void off(String destination) {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
BooleanMutex mutex = LOCAL_LOCK.get(destination);
|
||||||
|
if (mutex != null && mutex.state()) {
|
||||||
|
mutex.set(false);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
String path = SYN_SWITCH_ZK_NODE + destination;
|
||||||
|
try {
|
||||||
|
curatorClient.getCurator()
|
||||||
|
.create()
|
||||||
|
.creatingParentContainersIfNeeded()
|
||||||
|
.withMode(CreateMode.PERSISTENT)
|
||||||
|
.forPath(path, "off".getBytes(StandardCharsets.UTF_8));
|
||||||
|
} catch (Exception e) {
|
||||||
|
curatorClient.getCurator().setData().forPath(path, "off".getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void on(String destination) {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
BooleanMutex mutex = LOCAL_LOCK.get(destination);
|
||||||
|
if (mutex != null && !mutex.state()) {
|
||||||
|
mutex.set(true);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
String path = SYN_SWITCH_ZK_NODE + destination;
|
||||||
|
try {
|
||||||
|
curatorClient.getCurator()
|
||||||
|
.create()
|
||||||
|
.creatingParentContainersIfNeeded()
|
||||||
|
.withMode(CreateMode.PERSISTENT)
|
||||||
|
.forPath(path, "on".getBytes(StandardCharsets.UTF_8));
|
||||||
|
} catch (Exception e) {
|
||||||
|
curatorClient.getCurator().setData().forPath(path, "on".getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void release(String destination) {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
BooleanMutex mutex = LOCAL_LOCK.get(destination);
|
||||||
|
if (mutex != null && !mutex.state()) {
|
||||||
|
mutex.set(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (mode == Mode.DISTRIBUTED) {
|
||||||
|
BooleanMutex mutex = DISTRIBUTED_LOCK.get(destination);
|
||||||
|
if (mutex != null && !mutex.state()) {
|
||||||
|
mutex.set(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean status(String destination) {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
BooleanMutex mutex = LOCAL_LOCK.get(destination);
|
||||||
|
if (mutex != null) {
|
||||||
|
return mutex.state();
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
BooleanMutex mutex = DISTRIBUTED_LOCK.get(destination);
|
||||||
|
if (mutex != null) {
|
||||||
|
return mutex.state();
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void get(String destination) throws InterruptedException {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
BooleanMutex mutex = LOCAL_LOCK.get(destination);
|
||||||
|
if (mutex != null) {
|
||||||
|
mutex.get();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
BooleanMutex mutex = DISTRIBUTED_LOCK.get(destination);
|
||||||
|
if (mutex != null) {
|
||||||
|
mutex.get();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void get(String destination, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
|
||||||
|
if (mode == Mode.LOCAL) {
|
||||||
|
BooleanMutex mutex = LOCAL_LOCK.get(destination);
|
||||||
|
if (mutex != null) {
|
||||||
|
mutex.get(timeout, unit);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
BooleanMutex mutex = DISTRIBUTED_LOCK.get(destination);
|
||||||
|
if (mutex != null) {
|
||||||
|
mutex.get(timeout, unit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.config;
|
||||||
|
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.CanalClientConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* canal 的相关配置类
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "canal.conf")
|
||||||
|
public class AdapterCanalConfig extends CanalClientConfig {
|
||||||
|
|
||||||
|
public final Set<String> DESTINATIONS = new LinkedHashSet<>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setCanalInstances(List<CanalInstance> canalInstances) {
|
||||||
|
super.setCanalInstances(canalInstances);
|
||||||
|
|
||||||
|
if (canalInstances != null) {
|
||||||
|
synchronized (DESTINATIONS) {
|
||||||
|
DESTINATIONS.clear();
|
||||||
|
for (CanalInstance canalInstance : canalInstances) {
|
||||||
|
DESTINATIONS.add(canalInstance.getInstance());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setMqTopics(List<MQTopic> mqTopics) {
|
||||||
|
super.setMqTopics(mqTopics);
|
||||||
|
|
||||||
|
if (mqTopics != null) {
|
||||||
|
synchronized (DESTINATIONS) {
|
||||||
|
DESTINATIONS.clear();
|
||||||
|
for (MQTopic mqTopic : mqTopics) {
|
||||||
|
DESTINATIONS.add(mqTopic.getTopic());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.config;
|
||||||
|
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.alibaba.druid.pool.DruidDataSource;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.AdapterConfigs;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 适配器数据源及配置文件列表配置类
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "adapter.conf")
|
||||||
|
public class AdapterConfig {
|
||||||
|
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(AdapterConfig.class);
|
||||||
|
|
||||||
|
private Map<String, DatasourceConfig> datasourceConfigs;
|
||||||
|
|
||||||
|
private List<String> adapterConfigs;
|
||||||
|
|
||||||
|
public List<String> getAdapterConfigs() {
|
||||||
|
return adapterConfigs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, DatasourceConfig> getDatasourceConfigs() {
|
||||||
|
return datasourceConfigs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDatasourceConfigs(Map<String, DatasourceConfig> datasourceConfigs) {
|
||||||
|
this.datasourceConfigs = datasourceConfigs;
|
||||||
|
|
||||||
|
if (datasourceConfigs != null) {
|
||||||
|
for (Map.Entry<String, DatasourceConfig> entry : datasourceConfigs.entrySet()) {
|
||||||
|
DatasourceConfig datasourceConfig = entry.getValue();
|
||||||
|
// 加载数据源连接池
|
||||||
|
DruidDataSource ds = new DruidDataSource();
|
||||||
|
ds.setDriverClassName(datasourceConfig.getDriver());
|
||||||
|
ds.setUrl(datasourceConfig.getUrl());
|
||||||
|
ds.setUsername(datasourceConfig.getUsername());
|
||||||
|
ds.setPassword(datasourceConfig.getPassword());
|
||||||
|
ds.setInitialSize(1);
|
||||||
|
ds.setMinIdle(1);
|
||||||
|
ds.setMaxActive(datasourceConfig.getMaxActive());
|
||||||
|
ds.setMaxWait(60000);
|
||||||
|
ds.setTimeBetweenEvictionRunsMillis(60000);
|
||||||
|
ds.setMinEvictableIdleTimeMillis(300000);
|
||||||
|
ds.setPoolPreparedStatements(false);
|
||||||
|
ds.setMaxPoolPreparedStatementPerConnectionSize(20);
|
||||||
|
ds.setValidationQuery("select 1");
|
||||||
|
try {
|
||||||
|
ds.init();
|
||||||
|
} catch (SQLException e) {
|
||||||
|
logger.error("ERROR ## failed to initial datasource: " + datasourceConfig.getUrl(), e);
|
||||||
|
}
|
||||||
|
DatasourceConfig.DATA_SOURCES.put(entry.getKey(), ds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setAdapterConfigs(List<String> adapterConfigs) {
|
||||||
|
this.adapterConfigs = adapterConfigs;
|
||||||
|
|
||||||
|
if (adapterConfigs != null) {
|
||||||
|
AdapterConfigs.clear();
|
||||||
|
for (String adapterConfig : adapterConfigs) {
|
||||||
|
int idx = adapterConfig.indexOf("/");
|
||||||
|
if (idx > -1) {
|
||||||
|
String type = adapterConfig.substring(0, idx);
|
||||||
|
String ymlFile = adapterConfig.substring(idx + 1);
|
||||||
|
AdapterConfigs.put(type, ymlFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.config;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
|
||||||
|
import org.apache.curator.framework.CuratorFramework;
|
||||||
|
import org.apache.curator.framework.CuratorFrameworkFactory;
|
||||||
|
import org.apache.curator.retry.ExponentialBackoffRetry;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* curator 配置类
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class CuratorClient {
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private AdapterCanalConfig adapterCanalConfig;
|
||||||
|
|
||||||
|
private CuratorFramework curator = null;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
if (adapterCanalConfig.getZookeeperHosts() != null) {
|
||||||
|
curator = CuratorFrameworkFactory.builder()
|
||||||
|
.connectString(adapterCanalConfig.getZookeeperHosts())
|
||||||
|
.retryPolicy(new ExponentialBackoffRetry(1000, 3))
|
||||||
|
.sessionTimeoutMs(6000)
|
||||||
|
.connectionTimeoutMs(3000)
|
||||||
|
.namespace("canal-adapter")
|
||||||
|
.build();
|
||||||
|
curator.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public CuratorFramework getCurator() {
|
||||||
|
return curator;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.config;
|
||||||
|
|
||||||
|
import org.springframework.beans.BeansException;
|
||||||
|
import org.springframework.context.ApplicationContext;
|
||||||
|
import org.springframework.context.ApplicationContextAware;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* spring util配置类
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class SpringContext implements ApplicationContextAware {
|
||||||
|
|
||||||
|
private static ApplicationContext context;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 注入ApplicationContext
|
||||||
|
*/
|
||||||
|
public void setApplicationContext(final ApplicationContext context) throws BeansException {
|
||||||
|
// 在加载Spring时自动获得context
|
||||||
|
SpringContext.context = context;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object getBean(final String beanName) {
|
||||||
|
return SpringContext.context.getBean(beanName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object getBean(final Class<?> clz) {
|
||||||
|
return context.getBean(clz);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.loader;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.ExecutionException;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.common.SyncSwitch;
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.config.SpringContext;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.MessageUtil;
|
||||||
|
import com.alibaba.otter.canal.protocol.FlatMessage;
|
||||||
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 适配器工作线程抽象类
|
||||||
|
*
|
||||||
|
* @author rewerma 2018-8-19 下午11:30:49
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public abstract class AbstractCanalAdapterWorker {
|
||||||
|
|
||||||
|
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||||
|
|
||||||
|
protected String canalDestination; // canal实例
|
||||||
|
protected List<List<OuterAdapter>> canalOuterAdapters; // 外部适配器
|
||||||
|
protected ExecutorService groupInnerExecutorService; // 组内工作线程池
|
||||||
|
protected volatile boolean running = false; // 是否运行中
|
||||||
|
protected Thread thread = null;
|
||||||
|
protected Thread.UncaughtExceptionHandler handler = (t, e) -> logger.error("parse events has an error", e);
|
||||||
|
|
||||||
|
protected SyncSwitch syncSwitch;
|
||||||
|
|
||||||
|
public AbstractCanalAdapterWorker(List<List<OuterAdapter>> canalOuterAdapters){
|
||||||
|
this.canalOuterAdapters = canalOuterAdapters;
|
||||||
|
this.groupInnerExecutorService = Executors.newFixedThreadPool(canalOuterAdapters.size());
|
||||||
|
syncSwitch = (SyncSwitch) SpringContext.getBean(SyncSwitch.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void writeOut(final Message message) {
|
||||||
|
List<Future<Boolean>> futures = new ArrayList<>();
|
||||||
|
// 组间适配器并行运行
|
||||||
|
canalOuterAdapters.forEach(outerAdapters -> {
|
||||||
|
final List<OuterAdapter> adapters = outerAdapters;
|
||||||
|
futures.add(groupInnerExecutorService.submit(() -> {
|
||||||
|
try {
|
||||||
|
// 组内适配器穿行运行,尽量不要配置组内适配器
|
||||||
|
adapters.forEach(adapter -> {
|
||||||
|
long begin = System.currentTimeMillis();
|
||||||
|
MessageUtil.parse4Dml(canalDestination, message, adapter::sync);
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("{} elapsed time: {}",
|
||||||
|
adapter.getClass().getName(),
|
||||||
|
(System.currentTimeMillis() - begin));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// 等待所有适配器写入完成
|
||||||
|
// 由于是组间并发操作,所以将阻塞直到耗时最久的工作组操作完成
|
||||||
|
futures.forEach(future -> {
|
||||||
|
try {
|
||||||
|
if (!future.get()) {
|
||||||
|
logger.error("Outer adapter write failed");
|
||||||
|
}
|
||||||
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void writeOut(final FlatMessage flatMessage) {
|
||||||
|
List<Future<Boolean>> futures = new ArrayList<>();
|
||||||
|
// 组间适配器并行运行
|
||||||
|
canalOuterAdapters.forEach(outerAdapters -> {
|
||||||
|
futures.add(groupInnerExecutorService.submit(() -> {
|
||||||
|
try {
|
||||||
|
// 组内适配器穿行运行,尽量不要配置组内适配器
|
||||||
|
outerAdapters.forEach(adapter -> {
|
||||||
|
long begin = System.currentTimeMillis();
|
||||||
|
Dml dml = MessageUtil.flatMessage2Dml(canalDestination, flatMessage);
|
||||||
|
adapter.sync(dml);
|
||||||
|
if (logger.isDebugEnabled()) {
|
||||||
|
logger.debug("{} elapsed time: {}",
|
||||||
|
adapter.getClass().getName(),
|
||||||
|
(System.currentTimeMillis() - begin));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
// 等待所有适配器写入完成
|
||||||
|
// 由于是组间并发操作,所以将阻塞直到耗时最久的工作组操作完成
|
||||||
|
futures.forEach(future -> {
|
||||||
|
try {
|
||||||
|
if (!future.get()) {
|
||||||
|
logger.error("Outer adapter write failed");
|
||||||
|
}
|
||||||
|
} catch (InterruptedException | ExecutionException e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void start() {
|
||||||
|
if (!running) {
|
||||||
|
thread = new Thread(this::process);
|
||||||
|
thread.setUncaughtExceptionHandler(handler);
|
||||||
|
thread.start();
|
||||||
|
running = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract void process();
|
||||||
|
|
||||||
|
public void stop() {
|
||||||
|
try {
|
||||||
|
if (!running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
running = false;
|
||||||
|
|
||||||
|
syncSwitch.release(canalDestination);
|
||||||
|
|
||||||
|
logger.info("destination {} is waiting for adapters' worker thread die!", canalDestination);
|
||||||
|
if (thread != null) {
|
||||||
|
try {
|
||||||
|
thread.join();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
groupInnerExecutorService.shutdown();
|
||||||
|
logger.info("destination {} adapters worker thread dead!", canalDestination);
|
||||||
|
canalOuterAdapters.forEach(outerAdapters -> outerAdapters.forEach(OuterAdapter::destroy));
|
||||||
|
logger.info("destination {} all adapters destroyed!", canalDestination);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.loader;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.kafka.clients.consumer.CommitFailedException;
|
||||||
|
import org.apache.kafka.common.errors.WakeupException;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
|
import com.alibaba.otter.canal.client.kafka.KafkaCanalConnector;
|
||||||
|
import com.alibaba.otter.canal.client.kafka.KafkaCanalConnectors;
|
||||||
|
import com.alibaba.otter.canal.protocol.FlatMessage;
|
||||||
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* kafka对应的client适配器工作线程
|
||||||
|
*
|
||||||
|
* @author rewerma 2018-8-19 下午11:30:49
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class CanalAdapterKafkaWorker extends AbstractCanalAdapterWorker {
|
||||||
|
|
||||||
|
private KafkaCanalConnector connector;
|
||||||
|
private String topic;
|
||||||
|
private boolean flatMessage;
|
||||||
|
|
||||||
|
public CanalAdapterKafkaWorker(String bootstrapServers, String topic, String groupId,
|
||||||
|
List<List<OuterAdapter>> canalOuterAdapters, boolean flatMessage){
|
||||||
|
super(canalOuterAdapters);
|
||||||
|
this.topic = topic;
|
||||||
|
this.canalDestination = topic;
|
||||||
|
this.flatMessage = flatMessage;
|
||||||
|
this.connector = KafkaCanalConnectors.newKafkaConnector(bootstrapServers, topic, null, groupId, flatMessage);
|
||||||
|
// connector.setSessionTimeout(1L, TimeUnit.MINUTES);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void process() {
|
||||||
|
while (!running)
|
||||||
|
;
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
syncSwitch.get(canalDestination);
|
||||||
|
logger.info("=============> Start to connect topic: {} <=============", this.topic);
|
||||||
|
connector.connect();
|
||||||
|
logger.info("=============> Start to subscribe topic: {} <=============", this.topic);
|
||||||
|
connector.subscribe();
|
||||||
|
logger.info("=============> Subscribe topic: {} succeed <=============", this.topic);
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
Boolean status = syncSwitch.status(canalDestination);
|
||||||
|
if (status != null && !status) {
|
||||||
|
connector.disconnect();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<?> messages;
|
||||||
|
if (!flatMessage) {
|
||||||
|
messages = connector.getListWithoutAck(100L, TimeUnit.MILLISECONDS);
|
||||||
|
} else {
|
||||||
|
messages = connector.getFlatListWithoutAck(100L, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
if (messages != null) {
|
||||||
|
for (final Object message : messages) {
|
||||||
|
if (message instanceof FlatMessage) {
|
||||||
|
writeOut((FlatMessage) message);
|
||||||
|
} else {
|
||||||
|
writeOut((Message) message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
connector.ack();
|
||||||
|
} catch (CommitFailedException e) {
|
||||||
|
logger.warn(e.getMessage());
|
||||||
|
} catch (Throwable e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
TimeUnit.SECONDS.sleep(1L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
connector.unsubscribe();
|
||||||
|
} catch (WakeupException e) {
|
||||||
|
// No-op. Continue process
|
||||||
|
}
|
||||||
|
connector.disconnect();
|
||||||
|
logger.info("=============> Disconnect topic: {} <=============", this.topic);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.loader;
|
||||||
|
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.SocketAddress;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
|
import org.apache.commons.lang.StringUtils;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.CanalClientConfig;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.ExtensionLoader;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 外部适配器的加载器
|
||||||
|
*
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class CanalAdapterLoader {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(CanalAdapterLoader.class);
|
||||||
|
|
||||||
|
private CanalClientConfig canalClientConfig;
|
||||||
|
|
||||||
|
private Map<String, CanalAdapterWorker> canalWorkers = new HashMap<>();
|
||||||
|
|
||||||
|
private Map<String, AbstractCanalAdapterWorker> canalMQWorker = new HashMap<>();
|
||||||
|
|
||||||
|
private ExtensionLoader<OuterAdapter> loader;
|
||||||
|
|
||||||
|
public CanalAdapterLoader(CanalClientConfig canalClientConfig){
|
||||||
|
this.canalClientConfig = canalClientConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化canal-client
|
||||||
|
*/
|
||||||
|
public void init() {
|
||||||
|
loader = ExtensionLoader.getExtensionLoader(OuterAdapter.class);
|
||||||
|
|
||||||
|
String canalServerHost = this.canalClientConfig.getCanalServerHost();
|
||||||
|
SocketAddress sa = null;
|
||||||
|
if (canalServerHost != null) {
|
||||||
|
String[] ipPort = canalServerHost.split(":");
|
||||||
|
sa = new InetSocketAddress(ipPort[0], Integer.parseInt(ipPort[1]));
|
||||||
|
}
|
||||||
|
String zkHosts = this.canalClientConfig.getZookeeperHosts();
|
||||||
|
|
||||||
|
// 初始化canal-client的适配器
|
||||||
|
if (canalClientConfig.getCanalInstances() != null) {
|
||||||
|
for (CanalClientConfig.CanalInstance instance : canalClientConfig.getCanalInstances()) {
|
||||||
|
List<List<OuterAdapter>> canalOuterAdapterGroups = new ArrayList<>();
|
||||||
|
|
||||||
|
for (CanalClientConfig.Group connectorGroup : instance.getGroups()) {
|
||||||
|
List<OuterAdapter> canalOutConnectors = new ArrayList<>();
|
||||||
|
for (OuterAdapterConfig c : connectorGroup.getOutAdapters()) {
|
||||||
|
loadConnector(c, canalOutConnectors);
|
||||||
|
}
|
||||||
|
canalOuterAdapterGroups.add(canalOutConnectors);
|
||||||
|
}
|
||||||
|
CanalAdapterWorker worker;
|
||||||
|
if (sa != null) {
|
||||||
|
worker = new CanalAdapterWorker(instance.getInstance(), sa, canalOuterAdapterGroups);
|
||||||
|
} else if (zkHosts != null) {
|
||||||
|
worker = new CanalAdapterWorker(instance.getInstance(), zkHosts, canalOuterAdapterGroups);
|
||||||
|
} else {
|
||||||
|
throw new RuntimeException("No canal server connector found");
|
||||||
|
}
|
||||||
|
canalWorkers.put(instance.getInstance(), worker);
|
||||||
|
worker.start();
|
||||||
|
logger.info("Start adapter for canal instance: {} succeed", instance.getInstance());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化canal-client-mq的适配器
|
||||||
|
if (canalClientConfig.getMqTopics() != null) {
|
||||||
|
for (CanalClientConfig.MQTopic topic : canalClientConfig.getMqTopics()) {
|
||||||
|
for (CanalClientConfig.MQGroup group : topic.getGroups()) {
|
||||||
|
List<List<OuterAdapter>> canalOuterAdapterGroups = new ArrayList<>();
|
||||||
|
List<OuterAdapter> canalOuterAdapters = new ArrayList<>();
|
||||||
|
for (OuterAdapterConfig config : group.getOutAdapters()) {
|
||||||
|
loadConnector(config, canalOuterAdapters);
|
||||||
|
}
|
||||||
|
canalOuterAdapterGroups.add(canalOuterAdapters);
|
||||||
|
if (StringUtils.isBlank(topic.getMqMode()) || "rocketmq".equalsIgnoreCase(topic.getMqMode())) {
|
||||||
|
CanalAdapterRocketMQWorker rocketMQWorker = new CanalAdapterRocketMQWorker(canalClientConfig.getBootstrapServers(),
|
||||||
|
topic.getTopic(),
|
||||||
|
group.getGroupId(),
|
||||||
|
canalOuterAdapterGroups,
|
||||||
|
canalClientConfig.getFlatMessage());
|
||||||
|
canalMQWorker.put(topic.getTopic() + "-rocketmq-" + group.getGroupId(), rocketMQWorker);
|
||||||
|
rocketMQWorker.start();
|
||||||
|
} else if ("kafka".equalsIgnoreCase(topic.getMqMode())) {
|
||||||
|
CanalAdapterKafkaWorker canalKafkaWorker = new CanalAdapterKafkaWorker(canalClientConfig.getBootstrapServers(),
|
||||||
|
topic.getTopic(),
|
||||||
|
group.getGroupId(),
|
||||||
|
canalOuterAdapterGroups,
|
||||||
|
canalClientConfig.getFlatMessage());
|
||||||
|
canalMQWorker.put(topic.getTopic() + "-kafka-" + group.getGroupId(), canalKafkaWorker);
|
||||||
|
canalKafkaWorker.start();
|
||||||
|
}
|
||||||
|
logger.info("Start adapter for canal-client mq topic: {} succeed",
|
||||||
|
topic.getTopic() + "-" + group.getGroupId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void loadConnector(OuterAdapterConfig config, List<OuterAdapter> canalOutConnectors) {
|
||||||
|
try {
|
||||||
|
OuterAdapter adapter = loader.getExtension(config.getName());
|
||||||
|
ClassLoader cl = Thread.currentThread().getContextClassLoader();
|
||||||
|
// 替换ClassLoader
|
||||||
|
Thread.currentThread().setContextClassLoader(adapter.getClass().getClassLoader());
|
||||||
|
adapter.init(config);
|
||||||
|
Thread.currentThread().setContextClassLoader(cl);
|
||||||
|
canalOutConnectors.add(adapter);
|
||||||
|
logger.info("Load canal adapter: {} succeed", config.getName());
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("Load canal adapter: {} failed", config.getName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 销毁所有适配器 为防止canal实例太多造成销毁阻塞, 并行销毁
|
||||||
|
*/
|
||||||
|
public void destroy() {
|
||||||
|
if (canalWorkers.size() > 0) {
|
||||||
|
ExecutorService stopExecutorService = Executors.newFixedThreadPool(canalWorkers.size());
|
||||||
|
for (CanalAdapterWorker canalAdapterWorker : canalWorkers.values()) {
|
||||||
|
stopExecutorService.submit(canalAdapterWorker::stop);
|
||||||
|
}
|
||||||
|
stopExecutorService.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (canalMQWorker.size() > 0) {
|
||||||
|
ExecutorService stopMQWorkerService = Executors.newFixedThreadPool(canalMQWorker.size());
|
||||||
|
for (AbstractCanalAdapterWorker canalAdapterMQWorker : canalMQWorker.values()) {
|
||||||
|
stopMQWorkerService.submit(canalAdapterMQWorker::stop);
|
||||||
|
}
|
||||||
|
stopMQWorkerService.shutdown();
|
||||||
|
}
|
||||||
|
logger.info("All canal adapters destroyed");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.loader;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.kafka.common.errors.WakeupException;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
|
import com.alibaba.otter.canal.client.rocketmq.RocketMQCanalConnector;
|
||||||
|
import com.alibaba.otter.canal.client.rocketmq.RocketMQCanalConnectors;
|
||||||
|
import com.alibaba.otter.canal.protocol.FlatMessage;
|
||||||
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* rocketmq对应的client适配器工作线程
|
||||||
|
*
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class CanalAdapterRocketMQWorker extends AbstractCanalAdapterWorker {
|
||||||
|
|
||||||
|
private RocketMQCanalConnector connector;
|
||||||
|
private String topic;
|
||||||
|
private boolean flatMessage;
|
||||||
|
|
||||||
|
public CanalAdapterRocketMQWorker(String nameServers, String topic, String groupId,
|
||||||
|
List<List<OuterAdapter>> canalOuterAdapters, boolean flatMessage){
|
||||||
|
super(canalOuterAdapters);
|
||||||
|
this.topic = topic;
|
||||||
|
this.flatMessage = flatMessage;
|
||||||
|
this.canalDestination = topic;
|
||||||
|
this.connector = RocketMQCanalConnectors.newRocketMQConnector(nameServers, topic, groupId, flatMessage);
|
||||||
|
logger.info("RocketMQ consumer config topic:{}, nameServer:{}, groupId:{}", topic, nameServers, groupId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void process() {
|
||||||
|
while (!running)
|
||||||
|
;
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
syncSwitch.get(canalDestination);
|
||||||
|
logger.info("=============> Start to connect topic: {} <=============", this.topic);
|
||||||
|
connector.connect();
|
||||||
|
logger.info("=============> Start to subscribe topic: {}<=============", this.topic);
|
||||||
|
connector.subscribe();
|
||||||
|
logger.info("=============> Subscribe topic: {} succeed<=============", this.topic);
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
Boolean status = syncSwitch.status(canalDestination);
|
||||||
|
if (status != null && !status) {
|
||||||
|
connector.disconnect();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<?> messages;
|
||||||
|
if (!flatMessage) {
|
||||||
|
messages = connector.getListWithoutAck(100L, TimeUnit.MILLISECONDS);
|
||||||
|
} else {
|
||||||
|
messages = connector.getFlatListWithoutAck(100L, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
if (messages != null) {
|
||||||
|
for (final Object message : messages) {
|
||||||
|
if (message instanceof FlatMessage) {
|
||||||
|
writeOut((FlatMessage) message);
|
||||||
|
} else {
|
||||||
|
writeOut((Message) message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
connector.ack();
|
||||||
|
} catch (Throwable e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
TimeUnit.SECONDS.sleep(1L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
connector.unsubscribe();
|
||||||
|
} catch (WakeupException e) {
|
||||||
|
// No-op. Continue process
|
||||||
|
}
|
||||||
|
connector.disconnect();
|
||||||
|
logger.info("=============> Disconnect topic: {} <=============", this.topic);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.loader;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
import javax.annotation.PreDestroy;
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.common.SyncSwitch;
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.config.SpringContext;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.alibaba.druid.pool.DruidDataSource;
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.config.AdapterCanalConfig;
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.config.AdapterConfig;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.DatasourceConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 适配器启动业务类
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class CanalAdapterService {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(CanalAdapterService.class);
|
||||||
|
|
||||||
|
private static CanalAdapterLoader adapterLoader;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private AdapterCanalConfig adapterCanalConfig;
|
||||||
|
|
||||||
|
// 注入bean保证优先注册
|
||||||
|
@Resource
|
||||||
|
private AdapterConfig adapterConfig;
|
||||||
|
@Resource
|
||||||
|
private SpringContext springContext;
|
||||||
|
@Resource
|
||||||
|
private SyncSwitch syncSwitch;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
if (adapterLoader == null) {
|
||||||
|
try {
|
||||||
|
logger.info("## start the canal client adapters.");
|
||||||
|
adapterLoader = new CanalAdapterLoader(adapterCanalConfig);
|
||||||
|
adapterLoader.init();
|
||||||
|
logger.info("## the canal client adapters are running now ......");
|
||||||
|
} catch (Throwable e) {
|
||||||
|
logger.error("## something goes wrong when starting up the canal client adapters:", e);
|
||||||
|
System.exit(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void destroy() {
|
||||||
|
try {
|
||||||
|
logger.info("## stop the canal client adapters");
|
||||||
|
if (adapterLoader != null) {
|
||||||
|
adapterLoader.destroy();
|
||||||
|
}
|
||||||
|
for (DruidDataSource druidDataSource : DatasourceConfig.DATA_SOURCES.values()) {
|
||||||
|
try {
|
||||||
|
druidDataSource.close();
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Throwable e) {
|
||||||
|
logger.warn("## something goes wrong when stopping canal client adapters:", e);
|
||||||
|
} finally {
|
||||||
|
logger.info("## canal client adapters are down.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +1,21 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.loader;
|
package com.alibaba.otter.canal.adapter.launcher.loader;
|
||||||
|
|
||||||
import java.net.SocketAddress;
|
import java.net.SocketAddress;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.TimeoutException;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.CanalConnector;
|
import com.alibaba.otter.canal.client.CanalConnector;
|
||||||
import com.alibaba.otter.canal.client.CanalConnectors;
|
import com.alibaba.otter.canal.client.CanalConnectors;
|
||||||
import com.alibaba.otter.canal.client.adapter.CanalOuterAdapter;
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
import com.alibaba.otter.canal.client.impl.ClusterCanalConnector;
|
import com.alibaba.otter.canal.client.impl.ClusterCanalConnector;
|
||||||
|
import com.alibaba.otter.canal.client.impl.SimpleCanalConnector;
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 原生canal-server对应的client适配器工作线程
|
* 原生canal-server对应的client适配器工作线程
|
||||||
*
|
*
|
||||||
* @author machengyuan 2018-8-19 下午11:30:49
|
* @author rewrema 2018-8-19 下午11:30:49
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
public class CanalAdapterWorker extends AbstractCanalAdapterWorker {
|
public class CanalAdapterWorker extends AbstractCanalAdapterWorker {
|
||||||
@@ -31,10 +33,9 @@ public class CanalAdapterWorker extends AbstractCanalAdapterWorker {
|
|||||||
* @param canalOuterAdapters 外部适配器组
|
* @param canalOuterAdapters 外部适配器组
|
||||||
*/
|
*/
|
||||||
public CanalAdapterWorker(String canalDestination, SocketAddress address,
|
public CanalAdapterWorker(String canalDestination, SocketAddress address,
|
||||||
List<List<CanalOuterAdapter>> canalOuterAdapters){
|
List<List<OuterAdapter>> canalOuterAdapters){
|
||||||
this.canalOuterAdapters = canalOuterAdapters;
|
super(canalOuterAdapters);
|
||||||
this.canalDestination = canalDestination;
|
this.canalDestination = canalDestination;
|
||||||
groupInnerExecutorService = Executors.newFixedThreadPool(canalOuterAdapters.size());
|
|
||||||
connector = CanalConnectors.newSingleConnector(address, canalDestination, "", "");
|
connector = CanalConnectors.newSingleConnector(address, canalDestination, "", "");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,88 +47,35 @@ public class CanalAdapterWorker extends AbstractCanalAdapterWorker {
|
|||||||
* @param canalOuterAdapters 外部适配器组
|
* @param canalOuterAdapters 外部适配器组
|
||||||
*/
|
*/
|
||||||
public CanalAdapterWorker(String canalDestination, String zookeeperHosts,
|
public CanalAdapterWorker(String canalDestination, String zookeeperHosts,
|
||||||
List<List<CanalOuterAdapter>> canalOuterAdapters){
|
List<List<OuterAdapter>> canalOuterAdapters){
|
||||||
this.canalOuterAdapters = canalOuterAdapters;
|
super(canalOuterAdapters);
|
||||||
this.canalDestination = canalDestination;
|
this.canalDestination = canalDestination;
|
||||||
groupInnerExecutorService = Executors.newFixedThreadPool(canalOuterAdapters.size());
|
|
||||||
connector = CanalConnectors.newClusterConnector(zookeeperHosts, canalDestination, "", "");
|
connector = CanalConnectors.newClusterConnector(zookeeperHosts, canalDestination, "", "");
|
||||||
((ClusterCanalConnector) connector).setSoTimeout(SO_TIMEOUT);
|
((ClusterCanalConnector) connector).setSoTimeout(SO_TIMEOUT);
|
||||||
|
|
||||||
// super.initSwitcher(canalDestination);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void start() {
|
protected void process() {
|
||||||
if (!running) {
|
|
||||||
thread = new Thread(new Runnable() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
process();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
thread.setUncaughtExceptionHandler(handler);
|
|
||||||
thread.start();
|
|
||||||
running = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void stop() {
|
|
||||||
try {
|
|
||||||
if (!running) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// if (switcher != null && !switcher.state()) {
|
|
||||||
// switcher.set(true);
|
|
||||||
// }
|
|
||||||
|
|
||||||
connector.stopRunning();
|
|
||||||
running = false;
|
|
||||||
|
|
||||||
logger.info("destination {} is waiting for adapters' worker thread die!", canalDestination);
|
|
||||||
if (thread != null) {
|
|
||||||
try {
|
|
||||||
thread.join();
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
groupInnerExecutorService.shutdown();
|
|
||||||
logger.info("destination {} adapters' worker thread dead!", canalDestination);
|
|
||||||
for (List<CanalOuterAdapter> outerAdapters : canalOuterAdapters) {
|
|
||||||
for (CanalOuterAdapter adapter : outerAdapters) {
|
|
||||||
adapter.destroy();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
logger.info("destination {} all adapters destroyed!", canalDestination);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void process() {
|
|
||||||
while (!running)
|
while (!running)
|
||||||
; // waiting until running == true
|
; // waiting until running == true
|
||||||
while (running) {
|
while (running) {
|
||||||
try {
|
try {
|
||||||
// if (switcher != null) {
|
syncSwitch.get(canalDestination);
|
||||||
// switcher.get();
|
|
||||||
// }
|
|
||||||
logger.info("=============> Start to connect destination: {} <=============", this.canalDestination);
|
logger.info("=============> Start to connect destination: {} <=============", this.canalDestination);
|
||||||
connector.connect();
|
connector.connect();
|
||||||
logger.info("=============> Start to subscribe destination: {} <=============", this.canalDestination);
|
logger.info("=============> Start to subscribe destination: {} <=============", this.canalDestination);
|
||||||
connector.subscribe();
|
connector.subscribe();
|
||||||
logger.info("=============> Subscribe destination: {} succeed <=============", this.canalDestination);
|
logger.info("=============> Subscribe destination: {} succeed <=============", this.canalDestination);
|
||||||
while (running) {
|
while (running) {
|
||||||
// try {
|
try {
|
||||||
// if (switcher != null) {
|
syncSwitch.get(canalDestination, 1L, TimeUnit.MINUTES);
|
||||||
// switcher.get();
|
} catch (TimeoutException e) {
|
||||||
// }
|
break;
|
||||||
// } catch (TimeoutException e) {
|
}
|
||||||
// break;
|
if (!running) {
|
||||||
// }
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
// server配置canal.instance.network.soTimeout(默认: 30s)
|
// server配置canal.instance.network.soTimeout(默认: 30s)
|
||||||
// 范围内未与server交互,server将关闭本次socket连接
|
// 范围内未与server交互,server将关闭本次socket连接
|
||||||
@@ -135,13 +83,8 @@ public class CanalAdapterWorker extends AbstractCanalAdapterWorker {
|
|||||||
long batchId = message.getId();
|
long batchId = message.getId();
|
||||||
try {
|
try {
|
||||||
int size = message.getEntries().size();
|
int size = message.getEntries().size();
|
||||||
|
|
||||||
if (batchId == -1 || size == 0) {
|
if (batchId == -1 || size == 0) {
|
||||||
try {
|
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
} catch (InterruptedException e) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
if (logger.isDebugEnabled()) {
|
if (logger.isDebugEnabled()) {
|
||||||
logger.debug("destination: {} batchId: {} batchSize: {} ",
|
logger.debug("destination: {} batchId: {} batchSize: {} ",
|
||||||
@@ -151,18 +94,18 @@ public class CanalAdapterWorker extends AbstractCanalAdapterWorker {
|
|||||||
}
|
}
|
||||||
long begin = System.currentTimeMillis();
|
long begin = System.currentTimeMillis();
|
||||||
writeOut(message);
|
writeOut(message);
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
if (logger.isDebugEnabled()) {
|
if (logger.isDebugEnabled()) {
|
||||||
logger.debug("destination: {} batchId: {} elapsed time: {} ms",
|
logger.debug("destination: {} batchId: {} elapsed time: {} ms",
|
||||||
this.canalDestination,
|
this.canalDestination,
|
||||||
batchId,
|
batchId,
|
||||||
now - begin);
|
System.currentTimeMillis() - begin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
connector.ack(batchId); // 提交确认
|
connector.ack(batchId); // 提交确认
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
connector.rollback(batchId); // 处理失败, 回滚数据
|
connector.rollback(batchId); // 处理失败, 回滚数据
|
||||||
throw e;
|
logger.error("sync error!", e);
|
||||||
|
Thread.sleep(500);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,7 +123,40 @@ public class CanalAdapterWorker extends AbstractCanalAdapterWorker {
|
|||||||
// ignore
|
// ignore
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stop() {
|
||||||
|
try {
|
||||||
|
if (!running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connector instanceof ClusterCanalConnector) {
|
||||||
|
((ClusterCanalConnector) connector).stopRunning();
|
||||||
|
} else if (connector instanceof SimpleCanalConnector) {
|
||||||
|
((SimpleCanalConnector) connector).stopRunning();
|
||||||
|
}
|
||||||
|
|
||||||
|
running = false;
|
||||||
|
|
||||||
|
syncSwitch.release(canalDestination);
|
||||||
|
|
||||||
|
logger.info("destination {} is waiting for adapters' worker thread die!", canalDestination);
|
||||||
|
if (thread != null) {
|
||||||
|
try {
|
||||||
|
thread.join();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
groupInnerExecutorService.shutdown();
|
||||||
|
logger.info("destination {} adapters worker thread dead!", canalDestination);
|
||||||
|
canalOuterAdapters.forEach(outerAdapters -> outerAdapters.forEach(OuterAdapter::destroy));
|
||||||
|
logger.info("destination {} all adapters destroyed!", canalDestination);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
package com.alibaba.otter.canal.adapter.launcher.rest;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
import javax.annotation.PostConstruct;
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.common.EtlLock;
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.common.SyncSwitch;
|
||||||
|
import com.alibaba.otter.canal.adapter.launcher.config.AdapterCanalConfig;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.EtlResult;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.ExtensionLoader;
|
||||||
|
import com.alibaba.otter.canal.client.adapter.support.Result;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 适配器操作Rest
|
||||||
|
*
|
||||||
|
* @author rewerma @ 2018-10-20
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
public class CommonRest {
|
||||||
|
|
||||||
|
private static Logger logger = LoggerFactory.getLogger(CommonRest.class);
|
||||||
|
|
||||||
|
private static final String ETL_LOCK_ZK_NODE = "/sync-etl/";
|
||||||
|
|
||||||
|
private ExtensionLoader<OuterAdapter> loader;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private SyncSwitch syncSwitch;
|
||||||
|
@Resource
|
||||||
|
private EtlLock etlLock;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private AdapterCanalConfig adapterCanalConfig;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
loader = ExtensionLoader.getExtensionLoader(OuterAdapter.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ETL curl http://127.0.0.1:8081/etl/hbase/mytest_person2.yml -X POST
|
||||||
|
*
|
||||||
|
* @param type 类型 hbase, es
|
||||||
|
* @param task 任务名对应配置文件名 mytest_person2.yml
|
||||||
|
* @param params etl where条件参数, 为空全部导入
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@PostMapping("/etl/{type}/{task}")
|
||||||
|
public EtlResult etl(@PathVariable String type, @PathVariable String task,
|
||||||
|
@RequestParam(name = "params", required = false) String params) {
|
||||||
|
|
||||||
|
boolean locked = etlLock.tryLock(ETL_LOCK_ZK_NODE + type + "-" + task);
|
||||||
|
if (!locked) {
|
||||||
|
EtlResult result = new EtlResult();
|
||||||
|
result.setSucceeded(false);
|
||||||
|
result.setErrorMessage(task + " 有其他进程正在导入中, 请稍后再试");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
OuterAdapter adapter = loader.getExtension(type);
|
||||||
|
String destination = adapter.getDestination(task);
|
||||||
|
Boolean oriSwithcStatus = null;
|
||||||
|
if (destination != null) {
|
||||||
|
oriSwithcStatus = syncSwitch.status(destination);
|
||||||
|
syncSwitch.off(destination);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
List<String> paramArr = null;
|
||||||
|
if (params != null) {
|
||||||
|
String[] parmaArray = params.trim().split(";");
|
||||||
|
paramArr = Arrays.asList(parmaArray);
|
||||||
|
}
|
||||||
|
return adapter.etl(task, paramArr);
|
||||||
|
} finally {
|
||||||
|
if (destination != null && oriSwithcStatus != null && oriSwithcStatus) {
|
||||||
|
syncSwitch.on(destination);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
etlLock.unlock(ETL_LOCK_ZK_NODE + type + "-" + task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计总数 curl http://127.0.0.1:8081/count/hbase/mytest_person2.yml
|
||||||
|
*
|
||||||
|
* @param type 类型 hbase, es
|
||||||
|
* @param task 任务名对应配置文件名 mytest_person2.yml
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@GetMapping("/count/{type}/{task}")
|
||||||
|
public Map<String, Object> count(@PathVariable String type, @PathVariable String task) {
|
||||||
|
OuterAdapter adapter = loader.getExtension(type);
|
||||||
|
return adapter.count(task);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返回所有实例 curl http://127.0.0.1:8081/destinations
|
||||||
|
*/
|
||||||
|
@GetMapping("/destinations")
|
||||||
|
public List<Map<String, String>> destinations() {
|
||||||
|
List<Map<String, String>> result = new ArrayList<>();
|
||||||
|
Set<String> destinations = adapterCanalConfig.DESTINATIONS;
|
||||||
|
for (String destination : destinations) {
|
||||||
|
Map<String, String> resMap = new LinkedHashMap<>();
|
||||||
|
Boolean status = syncSwitch.status(destination);
|
||||||
|
String resStatus = "none";
|
||||||
|
if (status != null && status) {
|
||||||
|
resStatus = "on";
|
||||||
|
} else if (status != null && !status) {
|
||||||
|
resStatus = "off";
|
||||||
|
}
|
||||||
|
resMap.put("destination", destination);
|
||||||
|
resMap.put("status", resStatus);
|
||||||
|
result.add(resMap);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 实例同步开关 curl http://127.0.0.1:8081/syncSwitch/example/off -X PUT
|
||||||
|
*
|
||||||
|
* @param destination 实例名称
|
||||||
|
* @param status 开关状态: off on
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@PutMapping("/syncSwitch/{destination}/{status}")
|
||||||
|
public Result etl(@PathVariable String destination, @PathVariable String status) {
|
||||||
|
if (status.equals("on")) {
|
||||||
|
syncSwitch.on(destination);
|
||||||
|
logger.info("#Destination: {} sync on", destination);
|
||||||
|
return Result.createSuccess("实例: " + destination + " 开启同步成功");
|
||||||
|
} else if (status.equals("off")) {
|
||||||
|
syncSwitch.off(destination);
|
||||||
|
logger.info("#Destination: {} sync off", destination);
|
||||||
|
return Result.createSuccess("实例: " + destination + " 关闭同步成功");
|
||||||
|
} else {
|
||||||
|
Result result = new Result();
|
||||||
|
result.setCode(50000);
|
||||||
|
result.setMessage("实例: " + destination + " 操作失败");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取实例开关状态 curl http://127.0.0.1:8081/syncSwitch/example
|
||||||
|
*
|
||||||
|
* @param destination 实例名称
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
@GetMapping("/syncSwitch/{destination}")
|
||||||
|
public Map<String, String> etl(@PathVariable String destination) {
|
||||||
|
Boolean status = syncSwitch.status(destination);
|
||||||
|
String resStatus = "none";
|
||||||
|
if (status != null && status) {
|
||||||
|
resStatus = "on";
|
||||||
|
} else if (status != null && !status) {
|
||||||
|
resStatus = "off";
|
||||||
|
}
|
||||||
|
Map<String, String> res = new LinkedHashMap<>();
|
||||||
|
res.put("stauts", resStatus);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
}
|
||||||
54
client-adapter/launcher/src/main/resources/application.yml
Normal file
54
client-adapter/launcher/src/main/resources/application.yml
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
server:
|
||||||
|
port: 8081
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.alibaba.otter.canal.client.adapter.hbase: DEBUG
|
||||||
|
spring:
|
||||||
|
jackson:
|
||||||
|
date-format: yyyy-MM-dd HH:mm:ss
|
||||||
|
time-zone: GMT+8
|
||||||
|
default-property-inclusion: non_null
|
||||||
|
|
||||||
|
|
||||||
|
hbasezookeeper.quorum: 127.0.0.1
|
||||||
|
hbase.zookeeper.property.clientPort: 2181
|
||||||
|
hbase.zookeeper.znode.parent: /hbase
|
||||||
|
|
||||||
|
canal.conf:
|
||||||
|
canalServerHost: 127.0.0.1:11111
|
||||||
|
# zookeeperHosts: slave1:2181
|
||||||
|
# bootstrapServers: slave1:6667 #or rocketmq nameservers:host1:9876;host2:9876
|
||||||
|
flatMessage: true
|
||||||
|
canalInstances:
|
||||||
|
- instance: example
|
||||||
|
groups:
|
||||||
|
- outAdapters:
|
||||||
|
- name: logger
|
||||||
|
# - name: hbase
|
||||||
|
# properties:
|
||||||
|
# hbase.zookeeper.quorum: ${hbase.zookeeper.quorum}
|
||||||
|
# hbase.zookeeper.property.clientPort: ${hbase.zookeeper.property.clientPort}
|
||||||
|
# zookeeper.znode.parent: ${hbase.zookeeper.znode.parent}
|
||||||
|
# mqTopics:
|
||||||
|
# - mqMode: kafka
|
||||||
|
# topic: example
|
||||||
|
# groups:
|
||||||
|
# - groupId: g2
|
||||||
|
# outAdapters:
|
||||||
|
# - name: logger
|
||||||
|
# mqTopics:
|
||||||
|
# - mqMode: rocketmq
|
||||||
|
# topic: example
|
||||||
|
# groups:
|
||||||
|
# - groupId: g2
|
||||||
|
# outAdapters:
|
||||||
|
# - name: logger
|
||||||
|
|
||||||
|
#adapter.conf:
|
||||||
|
# datasourceConfigs:
|
||||||
|
# defaultDS:
|
||||||
|
# url: jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true
|
||||||
|
# username: root
|
||||||
|
# password: 121212
|
||||||
|
# adapterConfigs:
|
||||||
|
# - hbase/mytest_person2.yml
|
||||||
@@ -1,11 +1,9 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<parent>
|
<parent>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
<version>1.1.1</version>
|
||||||
</parent>
|
</parent>
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
@@ -21,6 +19,7 @@
|
|||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
|||||||
@@ -3,12 +3,10 @@ package com.alibaba.otter.canal.client.adapter.logger;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.CanalOuterAdapter;
|
import com.alibaba.otter.canal.client.adapter.OuterAdapter;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.CanalOuterAdapterConfiguration;
|
import com.alibaba.otter.canal.client.adapter.support.OuterAdapterConfig;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
import com.alibaba.otter.canal.client.adapter.support.Dml;
|
||||||
import com.alibaba.otter.canal.client.adapter.support.MessageUtil;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
import com.alibaba.otter.canal.client.adapter.support.SPI;
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 外部适配器示例
|
* 外部适配器示例
|
||||||
@@ -16,27 +14,21 @@ import com.alibaba.otter.canal.protocol.Message;
|
|||||||
* @author machengyuan 2018-8-19 下午11:45:38
|
* @author machengyuan 2018-8-19 下午11:45:38
|
||||||
* @version 1.0.0
|
* @version 1.0.0
|
||||||
*/
|
*/
|
||||||
@SPI("logger") // logger参数对应CanalOuterAdapterConfiguration配置中的name
|
@SPI("logger")
|
||||||
public class LoggerAdapterExample implements CanalOuterAdapter {
|
// logger参数对应CanalOuterAdapterConfiguration配置中的name
|
||||||
|
public class LoggerAdapterExample implements OuterAdapter {
|
||||||
|
|
||||||
private Logger logger = LoggerFactory.getLogger(this.getClass());
|
private Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void writeOut(Message message) {
|
public void init(OuterAdapterConfig configuration) {
|
||||||
// 直接输出日志信息
|
|
||||||
MessageUtil.parse4Dml(message, new MessageUtil.Consumer<Dml>() {
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void accept(Dml dml) {
|
public void sync(Dml dml) {
|
||||||
logger.info(dml.toString());
|
logger.info(dml.toString());
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void init(CanalOuterAdapterConfiguration configuration) {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void destroy() {
|
public void destroy() {
|
||||||
|
|||||||
@@ -1,21 +1,41 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<parent>
|
|
||||||
<artifactId>canal</artifactId>
|
|
||||||
<groupId>com.alibaba.otter</groupId>
|
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<artifactId>canal.client-adapter</artifactId>
|
<artifactId>canal.client-adapter</artifactId>
|
||||||
|
<version>1.1.1</version>
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
<name>canal client adapter module for otter ${project.version}</name>
|
<name>canal client adapter module for otter ${project.version}</name>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven.test.skip>true</maven.test.skip>
|
||||||
|
<downloadSources>true</downloadSources>
|
||||||
|
<java_source_version>1.8</java_source_version>
|
||||||
|
<java_target_version>1.8</java_target_version>
|
||||||
|
<file_encoding>UTF-8</file_encoding>
|
||||||
|
<canal_version>1.1.1-SNAPSHOT</canal_version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
<modules>
|
<modules>
|
||||||
<module>common</module>
|
<module>common</module>
|
||||||
<module>logger</module>
|
<module>logger</module>
|
||||||
<module>hbase</module>
|
<module>hbase</module>
|
||||||
|
<module>launcher</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.7.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${java_source_version}</source>
|
||||||
|
<target>${java_target_version}</target>
|
||||||
|
<encoding>${file_encoding}</encoding>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -1,149 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<parent>
|
|
||||||
<artifactId>canal</artifactId>
|
|
||||||
<groupId>com.alibaba.otter</groupId>
|
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.alibaba.otter</groupId>
|
|
||||||
<artifactId>canal.client-launcher</artifactId>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
<name>canal client launcher module for otter ${project.version}</name>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.alibaba.otter</groupId>
|
|
||||||
<artifactId>client-adapter.common</artifactId>
|
|
||||||
<version>${project.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.alibaba.otter</groupId>
|
|
||||||
<artifactId>canal.client</artifactId>
|
|
||||||
<version>${project.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<!-- 单独引入kafka依赖 -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.kafka</groupId>
|
|
||||||
<artifactId>kafka-clients</artifactId>
|
|
||||||
<version>1.1.1</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.yaml</groupId>
|
|
||||||
<artifactId>snakeyaml</artifactId>
|
|
||||||
<version>1.17</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<!-- outer adapter -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.alibaba.otter</groupId>
|
|
||||||
<artifactId>client-adapter.logger</artifactId>
|
|
||||||
<version>${project.version}</version>
|
|
||||||
<classifier>jar-with-dependencies</classifier>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.alibaba.otter</groupId>
|
|
||||||
<artifactId>client-adapter.hbase</artifactId>
|
|
||||||
<version>${project.version}</version>
|
|
||||||
<classifier>jar-with-dependencies</classifier>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<!-- deploy模块的packaging通常是jar,如果项目中没有java 源代码或资源文件,加上这一段配置使项目能通过构建 -->
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-jar-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<archive>
|
|
||||||
<addMavenDescriptor>true</addMavenDescriptor>
|
|
||||||
</archive>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/logback.xml</exclude>
|
|
||||||
<exclude>**/canal-client.yml</exclude>
|
|
||||||
</excludes>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
|
||||||
<!-- 这是最新版本,推荐使用这个版本 -->
|
|
||||||
<version>2.2.1</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>assemble</id>
|
|
||||||
<goals>
|
|
||||||
<goal>single</goal>
|
|
||||||
</goals>
|
|
||||||
<phase>package</phase>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
<configuration>
|
|
||||||
<appendAssemblyId>false</appendAssemblyId>
|
|
||||||
<attach>false</attach>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<profiles>
|
|
||||||
<profile>
|
|
||||||
<id>dev</id>
|
|
||||||
<activation>
|
|
||||||
<activeByDefault>true</activeByDefault>
|
|
||||||
<property>
|
|
||||||
<name>env</name>
|
|
||||||
<value>!release</value>
|
|
||||||
</property>
|
|
||||||
</activation>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<!-- maven assembly插件需要一个描述文件 来告诉插件包的结构以及打包所需的文件来自哪里 -->
|
|
||||||
<descriptors>
|
|
||||||
<descriptor>${basedir}/src/main/assembly/dev.xml</descriptor>
|
|
||||||
</descriptors>
|
|
||||||
<finalName>canal_client</finalName>
|
|
||||||
<outputDirectory>${project.build.directory}</outputDirectory>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
</profile>
|
|
||||||
|
|
||||||
<profile>
|
|
||||||
<id>release</id>
|
|
||||||
<activation>
|
|
||||||
<property>
|
|
||||||
<name>env</name>
|
|
||||||
<value>release</value>
|
|
||||||
</property>
|
|
||||||
</activation>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<!-- 发布模式使用的maven assembly插件描述文件 -->
|
|
||||||
<descriptors>
|
|
||||||
<descriptor>${basedir}/src/main/assembly/release.xml</descriptor>
|
|
||||||
</descriptors>
|
|
||||||
<!-- 如果一个应用的包含多个deploy模块,如果使用同样的包名, 如果把它们复制的一个目录中可能会失败,所以包名加了 artifactId以示区分 -->
|
|
||||||
<finalName>${project.artifactId}-${project.version}</finalName>
|
|
||||||
<!-- scm 要求 release 模式打出的包放到顶级目录下的target子目录中 -->
|
|
||||||
<outputDirectory>${project.parent.build.directory}</outputDirectory>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
</profile>
|
|
||||||
</profiles>
|
|
||||||
|
|
||||||
</project>
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
|
|
||||||
<id>dist</id>
|
|
||||||
<formats>
|
|
||||||
<format>dir</format>
|
|
||||||
</formats>
|
|
||||||
<includeBaseDirectory>false</includeBaseDirectory>
|
|
||||||
<fileSets>
|
|
||||||
<fileSet>
|
|
||||||
<directory>.</directory>
|
|
||||||
<outputDirectory>/</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>README*</include>
|
|
||||||
</includes>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
|
||||||
<directory>./src/main/bin</directory>
|
|
||||||
<outputDirectory>bin</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>**/*</include>
|
|
||||||
</includes>
|
|
||||||
<fileMode>0755</fileMode>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
|
||||||
<directory>./src/main/conf</directory>
|
|
||||||
<outputDirectory>/conf</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>**/*</include>
|
|
||||||
</includes>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
|
||||||
<directory>./src/main/resources</directory>
|
|
||||||
<outputDirectory>/conf</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>**/*</include>
|
|
||||||
</includes>
|
|
||||||
<excludes>
|
|
||||||
<exclude>META-INF/**</exclude>
|
|
||||||
</excludes>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
|
||||||
<directory>target</directory>
|
|
||||||
<outputDirectory>logs</outputDirectory>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/*</exclude>
|
|
||||||
</excludes>
|
|
||||||
</fileSet>
|
|
||||||
</fileSets>
|
|
||||||
<dependencySets>
|
|
||||||
<dependencySet>
|
|
||||||
<outputDirectory>lib</outputDirectory>
|
|
||||||
<excludes>
|
|
||||||
<exclude>junit:junit</exclude>
|
|
||||||
</excludes>
|
|
||||||
</dependencySet>
|
|
||||||
</dependencySets>
|
|
||||||
</assembly>
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
|
|
||||||
<id>dist</id>
|
|
||||||
<formats>
|
|
||||||
<format>tar.gz</format>
|
|
||||||
</formats>
|
|
||||||
<includeBaseDirectory>false</includeBaseDirectory>
|
|
||||||
<fileSets>
|
|
||||||
<fileSet>
|
|
||||||
<directory>.</directory>
|
|
||||||
<outputDirectory>/</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>README*</include>
|
|
||||||
</includes>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
|
||||||
<directory>./src/main/bin</directory>
|
|
||||||
<outputDirectory>bin</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>**/*</include>
|
|
||||||
</includes>
|
|
||||||
<fileMode>0755</fileMode>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
|
||||||
<directory>./src/main/conf</directory>
|
|
||||||
<outputDirectory>/conf</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>**/*</include>
|
|
||||||
</includes>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
|
||||||
<directory>./src/main/resources</directory>
|
|
||||||
<outputDirectory>/conf</outputDirectory>
|
|
||||||
<includes>
|
|
||||||
<include>**/*</include>
|
|
||||||
</includes>
|
|
||||||
<excludes>
|
|
||||||
<exclude>META-INF/**</exclude>
|
|
||||||
</excludes>
|
|
||||||
</fileSet>
|
|
||||||
<fileSet>
|
|
||||||
<directory>target</directory>
|
|
||||||
<outputDirectory>logs</outputDirectory>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/*</exclude>
|
|
||||||
</excludes>
|
|
||||||
</fileSet>
|
|
||||||
</fileSets>
|
|
||||||
<dependencySets>
|
|
||||||
<dependencySet>
|
|
||||||
<outputDirectory>lib</outputDirectory>
|
|
||||||
<excludes>
|
|
||||||
<exclude>junit:junit</exclude>
|
|
||||||
</excludes>
|
|
||||||
</dependencySet>
|
|
||||||
</dependencySets>
|
|
||||||
</assembly>
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
@echo off
|
|
||||||
@if not "%ECHO%" == "" echo %ECHO%
|
|
||||||
@if "%OS%" == "Windows_NT" setlocal
|
|
||||||
|
|
||||||
set ENV_PATH=.\
|
|
||||||
if "%OS%" == "Windows_NT" set ENV_PATH=%~dp0%
|
|
||||||
|
|
||||||
set conf_dir=%ENV_PATH%\..\conf
|
|
||||||
set canal_conf=%conf_dir%\canal-client.yml
|
|
||||||
set logback_configurationFile=%conf_dir%\logback.xml
|
|
||||||
|
|
||||||
set CLASSPATH=%conf_dir%
|
|
||||||
set CLASSPATH=%conf_dir%\..\lib\*;%CLASSPATH%
|
|
||||||
|
|
||||||
set JAVA_MEM_OPTS= -Xms128m -Xmx512m -XX:PermSize=128m
|
|
||||||
set JAVA_OPTS_EXT= -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Dapplication.codeset=UTF-8 -Dfile.encoding=UTF-8
|
|
||||||
set JAVA_DEBUG_OPT= -server -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=9099,server=y,suspend=n
|
|
||||||
set CANAL_OPTS= -DappName=otter-canal -Dlogback.configurationFile="%logback_configurationFile%" -Dcanal.conf="%canal_conf%"
|
|
||||||
|
|
||||||
set JAVA_OPTS= %JAVA_MEM_OPTS% %JAVA_OPTS_EXT% %JAVA_DEBUG_OPT% %CANAL_OPTS%
|
|
||||||
|
|
||||||
set CMD_STR= java %JAVA_OPTS% -classpath "%CLASSPATH%" java %JAVA_OPTS% -classpath "%CLASSPATH%" com.alibaba.otter.canal.client.ClientLauncher
|
|
||||||
echo start cmd : %CMD_STR%
|
|
||||||
|
|
||||||
java %JAVA_OPTS% -classpath "%CLASSPATH%" com.alibaba.otter.canal.client.ClientLauncher
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
current_path=`pwd`
|
|
||||||
case "`uname`" in
|
|
||||||
Linux)
|
|
||||||
bin_abs_path=$(readlink -f $(dirname $0))
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
bin_abs_path=`cd $(dirname $0); pwd`
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
base=${bin_abs_path}/..
|
|
||||||
canal_conf=$base/conf/canal-client.yml
|
|
||||||
logback_configurationFile=$base/conf/logback.xml
|
|
||||||
export LANG=en_US.UTF-8
|
|
||||||
export BASE=$base
|
|
||||||
|
|
||||||
if [ -f $base/bin/canal_client.pid ] ; then
|
|
||||||
echo "found canal_client.pid , Please run stop.sh first ,then startup.sh" 2>&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
## set java path
|
|
||||||
if [ -z "$JAVA" ] ; then
|
|
||||||
JAVA=$(which java)
|
|
||||||
fi
|
|
||||||
|
|
||||||
ALIBABA_JAVA="/usr/alibaba/java/bin/java"
|
|
||||||
TAOBAO_JAVA="/opt/taobao/java/bin/java"
|
|
||||||
if [ -z "$JAVA" ]; then
|
|
||||||
if [ -f $ALIBABA_JAVA ] ; then
|
|
||||||
JAVA=$ALIBABA_JAVA
|
|
||||||
elif [ -f $TAOBAO_JAVA ] ; then
|
|
||||||
JAVA=$TAOBAO_JAVA
|
|
||||||
else
|
|
||||||
echo "Cannot find a Java JDK. Please set either set JAVA or put java (>=1.5) in your PATH." 2>&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
case "$#"
|
|
||||||
in
|
|
||||||
0 )
|
|
||||||
;;
|
|
||||||
1 )
|
|
||||||
var=$*
|
|
||||||
if [ -f $var ] ; then
|
|
||||||
canal_conf=$var
|
|
||||||
else
|
|
||||||
echo "THE PARAMETER IS NOT CORRECT.PLEASE CHECK AGAIN."
|
|
||||||
exit
|
|
||||||
fi;;
|
|
||||||
2 )
|
|
||||||
var=$1
|
|
||||||
if [ -f $var ] ; then
|
|
||||||
canal_conf=$var
|
|
||||||
else
|
|
||||||
if [ "$1" = "debug" ]; then
|
|
||||||
DEBUG_PORT=$2
|
|
||||||
DEBUG_SUSPEND="n"
|
|
||||||
JAVA_DEBUG_OPT="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=$DEBUG_PORT,server=y,suspend=$DEBUG_SUSPEND"
|
|
||||||
fi
|
|
||||||
fi;;
|
|
||||||
* )
|
|
||||||
echo "THE PARAMETERS MUST BE TWO OR LESS.PLEASE CHECK AGAIN."
|
|
||||||
exit;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
str=`file -L $JAVA | grep 64-bit`
|
|
||||||
if [ -n "$str" ]; then
|
|
||||||
JAVA_OPTS="-server -Xms2048m -Xmx3072m -Xmn1024m -XX:SurvivorRatio=2 -XX:PermSize=96m -XX:MaxPermSize=256m -Xss256k -XX:-UseAdaptiveSizePolicy -XX:MaxTenuringThreshold=15 -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError"
|
|
||||||
else
|
|
||||||
JAVA_OPTS="-server -Xms1024m -Xmx1024m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:MaxPermSize=128m "
|
|
||||||
fi
|
|
||||||
|
|
||||||
JAVA_OPTS=" $JAVA_OPTS -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Dfile.encoding=UTF-8"
|
|
||||||
CANAL_OPTS="-DappName=otter-canal-client -Dlogback.configurationFile=$logback_configurationFile -Dcanal.conf=$canal_conf"
|
|
||||||
|
|
||||||
if [ -e $canal_conf -a -e $logback_configurationFile ]
|
|
||||||
then
|
|
||||||
|
|
||||||
for i in $base/lib/*;
|
|
||||||
do CLASSPATH=$i:"$CLASSPATH";
|
|
||||||
done
|
|
||||||
CLASSPATH="$base/conf:$CLASSPATH";
|
|
||||||
|
|
||||||
echo "cd to $bin_abs_path for workaround relative path"
|
|
||||||
cd $bin_abs_path
|
|
||||||
|
|
||||||
echo LOG CONFIGURATION : $logback_configurationFile
|
|
||||||
echo canal conf : $canal_conf
|
|
||||||
echo CLASSPATH :$CLASSPATH
|
|
||||||
$JAVA $JAVA_OPTS $JAVA_DEBUG_OPT $CANAL_OPTS -classpath .:$CLASSPATH com.alibaba.otter.canal.client.ClientLauncher 1>>$base/logs/canal_client.log 2>&1 &
|
|
||||||
echo $! > $base/bin/canal_client.pid
|
|
||||||
|
|
||||||
echo "cd to $current_path for continue"
|
|
||||||
cd $current_path
|
|
||||||
else
|
|
||||||
echo "canal client conf("$canal_conf") OR log configration file($logback_configurationFile) is not exist,please create then first!"
|
|
||||||
fi
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
cygwin=false;
|
|
||||||
linux=false;
|
|
||||||
case "`uname`" in
|
|
||||||
CYGWIN*)
|
|
||||||
cygwin=true
|
|
||||||
;;
|
|
||||||
Linux*)
|
|
||||||
linux=true
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
get_pid() {
|
|
||||||
STR=$1
|
|
||||||
PID=$2
|
|
||||||
if $cygwin; then
|
|
||||||
JAVA_CMD="$JAVA_HOME\bin\java"
|
|
||||||
JAVA_CMD=`cygpath --path --unix $JAVA_CMD`
|
|
||||||
JAVA_PID=`ps |grep $JAVA_CMD |awk '{print $1}'`
|
|
||||||
else
|
|
||||||
if $linux; then
|
|
||||||
if [ ! -z "$PID" ]; then
|
|
||||||
JAVA_PID=`ps -C java -f --width 1000|grep "$STR"|grep "$PID"|grep -v grep|awk '{print $2}'`
|
|
||||||
else
|
|
||||||
JAVA_PID=`ps -C java -f --width 1000|grep "$STR"|grep -v grep|awk '{print $2}'`
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
if [ ! -z "$PID" ]; then
|
|
||||||
JAVA_PID=`ps aux |grep "$STR"|grep "$PID"|grep -v grep|awk '{print $2}'`
|
|
||||||
else
|
|
||||||
JAVA_PID=`ps aux |grep "$STR"|grep -v grep|awk '{print $2}'`
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
echo $JAVA_PID;
|
|
||||||
}
|
|
||||||
|
|
||||||
base=`dirname $0`/..
|
|
||||||
pidfile=$base/bin/canal_client.pid
|
|
||||||
if [ ! -f "$pidfile" ];then
|
|
||||||
echo "canal client is not running. exists"
|
|
||||||
exit
|
|
||||||
fi
|
|
||||||
|
|
||||||
pid=`cat $pidfile`
|
|
||||||
if [ "$pid" == "" ] ; then
|
|
||||||
pid=`get_pid "appName=otter-canal-client"`
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo -e "`hostname`: stopping canal $pid ... "
|
|
||||||
kill $pid
|
|
||||||
|
|
||||||
LOOPS=0
|
|
||||||
while (true);
|
|
||||||
do
|
|
||||||
gpid=`get_pid "appName=otter-canal-client" "$pid"`
|
|
||||||
if [ "$gpid" == "" ] ; then
|
|
||||||
echo "Oook! cost:$LOOPS"
|
|
||||||
`rm $pidfile`
|
|
||||||
break;
|
|
||||||
fi
|
|
||||||
let LOOPS=LOOPS+1
|
|
||||||
sleep 1
|
|
||||||
done
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.loader.CanalAdapterLoader;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.CanalClientConfig;
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.yaml.snakeyaml.Yaml;
|
|
||||||
|
|
||||||
import java.io.FileInputStream;
|
|
||||||
|
|
||||||
public class ClientLauncher {
|
|
||||||
|
|
||||||
private static final String CLASSPATH_URL_PREFIX = "classpath:";
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(ClientLauncher.class);
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
try {
|
|
||||||
logger.info("## set default uncaught exception handler");
|
|
||||||
setGlobalUncaughtExceptionHandler();
|
|
||||||
|
|
||||||
logger.info("## load canal client configurations");
|
|
||||||
String conf = System.getProperty("client.conf", "classpath:canal-client.yml");
|
|
||||||
CanalClientConfig canalClientConfig;
|
|
||||||
if (conf.startsWith(CLASSPATH_URL_PREFIX)) {
|
|
||||||
conf = StringUtils.substringAfter(conf, CLASSPATH_URL_PREFIX);
|
|
||||||
canalClientConfig = new Yaml().loadAs(ClientLauncher.class.getClassLoader().getResourceAsStream(conf),
|
|
||||||
CanalClientConfig.class);
|
|
||||||
} else {
|
|
||||||
canalClientConfig = new Yaml().loadAs(new FileInputStream(conf), CanalClientConfig.class);
|
|
||||||
}
|
|
||||||
logger.info("## start the canal client adapters.");
|
|
||||||
final CanalAdapterLoader adapterLoader = new CanalAdapterLoader(canalClientConfig);
|
|
||||||
adapterLoader.init();
|
|
||||||
logger.info("## the canal client adapters are running now ......");
|
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread() {
|
|
||||||
|
|
||||||
public void run() {
|
|
||||||
try {
|
|
||||||
logger.info("## stop the canal client adapters");
|
|
||||||
adapterLoader.destroy();
|
|
||||||
} catch (Throwable e) {
|
|
||||||
logger.warn("## something goes wrong when stopping canal client adapters:", e);
|
|
||||||
} finally {
|
|
||||||
logger.info("## canal client adapters are down.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
});
|
|
||||||
} catch (Throwable e) {
|
|
||||||
logger.error("## something goes wrong when starting up the canal client adapters:", e);
|
|
||||||
System.exit(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void setGlobalUncaughtExceptionHandler() {
|
|
||||||
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void uncaughtException(Thread t, Throwable e) {
|
|
||||||
logger.error("UnCaughtException", e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.loader;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.Callable;
|
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Future;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.CanalOuterAdapter;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 适配器工作线程抽象类
|
|
||||||
*
|
|
||||||
* @author machengyuan 2018-8-19 下午11:30:49
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
public abstract class AbstractCanalAdapterWorker {
|
|
||||||
|
|
||||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
|
||||||
|
|
||||||
protected String canalDestination; // canal实例
|
|
||||||
protected List<List<CanalOuterAdapter>> canalOuterAdapters; // 外部适配器
|
|
||||||
protected ExecutorService groupInnerExecutorService; // 组内工作线程池
|
|
||||||
protected volatile boolean running = false; // 是否运行中
|
|
||||||
protected Thread thread = null;
|
|
||||||
protected Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void uncaughtException(Thread t, Throwable e) {
|
|
||||||
logger.error("parse events has an error", e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
protected void writeOut(final Message message) {
|
|
||||||
List<Future<Boolean>> futures = new ArrayList<>();
|
|
||||||
// 组间适配器并行运行
|
|
||||||
for (List<CanalOuterAdapter> outerAdapters : canalOuterAdapters) {
|
|
||||||
final List<CanalOuterAdapter> adapters = outerAdapters;
|
|
||||||
futures.add(groupInnerExecutorService.submit(new Callable<Boolean>() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean call() {
|
|
||||||
try {
|
|
||||||
// 组内适配器穿行运行,尽量不要配置组内适配器
|
|
||||||
for (CanalOuterAdapter c : adapters) {
|
|
||||||
long begin = System.currentTimeMillis();
|
|
||||||
c.writeOut(message);
|
|
||||||
if (logger.isDebugEnabled()) {
|
|
||||||
logger.debug("{} elapsed time: {}",
|
|
||||||
c.getClass().getName(),
|
|
||||||
(System.currentTimeMillis() - begin));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
} catch (Exception e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
// 等待所有适配器写入完成
|
|
||||||
// 由于是组间并发操作,所以将阻塞直到耗时最久的工作组操作完成
|
|
||||||
for (Future<Boolean> f : futures) {
|
|
||||||
try {
|
|
||||||
if (!f.get()) {
|
|
||||||
logger.error("Outer adapter write failed");
|
|
||||||
}
|
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
|
||||||
logger.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public abstract void start();
|
|
||||||
|
|
||||||
public abstract void stop();
|
|
||||||
}
|
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.loader;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
|
||||||
|
|
||||||
import org.apache.kafka.clients.consumer.CommitFailedException;
|
|
||||||
import org.apache.kafka.common.errors.WakeupException;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.CanalOuterAdapter;
|
|
||||||
import com.alibaba.otter.canal.client.kafka.KafkaCanalConnector;
|
|
||||||
import com.alibaba.otter.canal.client.kafka.KafkaCanalConnectors;
|
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* kafka对应的client适配器工作线程
|
|
||||||
*
|
|
||||||
* @author machengyuan 2018-8-19 下午11:30:49
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
public class CanalAdapterKafkaWorker extends AbstractCanalAdapterWorker {
|
|
||||||
|
|
||||||
private KafkaCanalConnector connector;
|
|
||||||
|
|
||||||
private String topic;
|
|
||||||
|
|
||||||
public CanalAdapterKafkaWorker(String zkServers, String bootstrapServers, String topic, String groupId,
|
|
||||||
List<List<CanalOuterAdapter>> canalOuterAdapters){
|
|
||||||
this.canalOuterAdapters = canalOuterAdapters;
|
|
||||||
this.groupInnerExecutorService = Executors.newFixedThreadPool(canalOuterAdapters.size());
|
|
||||||
this.topic = topic;
|
|
||||||
this.canalDestination = topic;
|
|
||||||
connector = KafkaCanalConnectors.newKafkaConnector(zkServers, bootstrapServers, topic, null, groupId);
|
|
||||||
// connector.setSessionTimeout(5L, TimeUnit.MINUTES);
|
|
||||||
|
|
||||||
// super.initSwitcher(topic);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void start() {
|
|
||||||
if (!running) {
|
|
||||||
thread = new Thread(new Runnable() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
process();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
thread.setUncaughtExceptionHandler(handler);
|
|
||||||
running = true;
|
|
||||||
thread.start();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void stop() {
|
|
||||||
try {
|
|
||||||
if (!running) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
connector.stopRunning();
|
|
||||||
running = false;
|
|
||||||
|
|
||||||
// if (switcher != null && !switcher.state()) {
|
|
||||||
// switcher.set(true);
|
|
||||||
// }
|
|
||||||
|
|
||||||
if (thread != null) {
|
|
||||||
try {
|
|
||||||
thread.join();
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
}
|
|
||||||
groupInnerExecutorService.shutdown();
|
|
||||||
logger.info("topic {} connectors' worker thread dead!", this.topic);
|
|
||||||
for (List<CanalOuterAdapter> outerAdapters : canalOuterAdapters) {
|
|
||||||
for (CanalOuterAdapter adapter : outerAdapters) {
|
|
||||||
adapter.destroy();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
logger.info("topic {} all connectors destroyed!", this.topic);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void process() {
|
|
||||||
while (!running)
|
|
||||||
;
|
|
||||||
ExecutorService executor = Executors.newSingleThreadExecutor();
|
|
||||||
final AtomicBoolean executing = new AtomicBoolean(true);
|
|
||||||
while (running) {
|
|
||||||
try {
|
|
||||||
logger.info("=============> Start to connect topic: {} <=============", this.topic);
|
|
||||||
connector.connect();
|
|
||||||
logger.info("=============> Start to subscribe topic: {} <=============", this.topic);
|
|
||||||
connector.subscribe();
|
|
||||||
logger.info("=============> Subscribe topic: {} succeed <=============", this.topic);
|
|
||||||
while (running) {
|
|
||||||
try {
|
|
||||||
// switcher.get(); //等待开关开启
|
|
||||||
|
|
||||||
final Message message = connector.getWithoutAck();
|
|
||||||
|
|
||||||
executing.set(true);
|
|
||||||
if (message != null) {
|
|
||||||
executor.submit(new Runnable() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
try {
|
|
||||||
if (logger.isDebugEnabled()) {
|
|
||||||
logger.debug("topic: {} batchId: {} batchSize: {} ",
|
|
||||||
topic,
|
|
||||||
message.getId(),
|
|
||||||
message.getEntries().size());
|
|
||||||
}
|
|
||||||
long begin = System.currentTimeMillis();
|
|
||||||
writeOut(message);
|
|
||||||
long now = System.currentTimeMillis();
|
|
||||||
if ((System.currentTimeMillis() - begin) > 5 * 60 * 1000) {
|
|
||||||
logger.error("topic: {} batchId {} elapsed time: {} ms",
|
|
||||||
topic,
|
|
||||||
message.getId(),
|
|
||||||
now - begin);
|
|
||||||
}
|
|
||||||
if (logger.isDebugEnabled()) {
|
|
||||||
logger.debug("topic: {} batchId {} elapsed time: {} ms",
|
|
||||||
topic,
|
|
||||||
message.getId(),
|
|
||||||
now - begin);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage(), e);
|
|
||||||
} finally {
|
|
||||||
executing.compareAndSet(true, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 间隔一段时间ack一次, 防止因超时未响应切换到另外台客户端
|
|
||||||
long currentTS = System.currentTimeMillis();
|
|
||||||
while (executing.get()) {
|
|
||||||
// 大于1分钟未消费完ack一次keep alive
|
|
||||||
if (System.currentTimeMillis() - currentTS > 60000) {
|
|
||||||
connector.ack();
|
|
||||||
currentTS = System.currentTimeMillis();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
connector.ack();
|
|
||||||
}
|
|
||||||
} catch (CommitFailedException e) {
|
|
||||||
logger.warn(e.getMessage());
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage(), e);
|
|
||||||
TimeUnit.SECONDS.sleep(1L);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
executor.shutdown();
|
|
||||||
|
|
||||||
try {
|
|
||||||
connector.unsubscribe();
|
|
||||||
} catch (WakeupException e) {
|
|
||||||
// No-op. Continue process
|
|
||||||
}
|
|
||||||
connector.disconnnect();
|
|
||||||
logger.info("=============> Disconnect topic: {} <=============", this.topic);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,170 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.adapter.loader;
|
|
||||||
|
|
||||||
import java.net.InetSocketAddress;
|
|
||||||
import java.net.SocketAddress;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.adapter.CanalOuterAdapter;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.CanalClientConfig;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.CanalOuterAdapterConfiguration;
|
|
||||||
import com.alibaba.otter.canal.client.adapter.support.ExtensionLoader;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 外部适配器的加载器
|
|
||||||
*
|
|
||||||
* @author machengyuan 2018-8-19 下午11:45:49
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
public class CanalAdapterLoader {
|
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(CanalAdapterLoader.class);
|
|
||||||
|
|
||||||
private CanalClientConfig canalClientConfig;
|
|
||||||
|
|
||||||
private Map<String, CanalAdapterWorker> canalWorkers = new HashMap<>();
|
|
||||||
|
|
||||||
private Map<String, CanalAdapterKafkaWorker> canalKafkaWorkers = new HashMap<>();
|
|
||||||
|
|
||||||
private ExtensionLoader<CanalOuterAdapter> loader;
|
|
||||||
|
|
||||||
public CanalAdapterLoader(CanalClientConfig canalClientConfig){
|
|
||||||
this.canalClientConfig = canalClientConfig;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 初始化canal-client、 canal-client-kafka的适配器
|
|
||||||
*/
|
|
||||||
public void init() {
|
|
||||||
// canal instances 和 kafka topics 配置不能同时为空
|
|
||||||
if (canalClientConfig.getCanalInstances() == null && canalClientConfig.getKafkaTopics() == null) {
|
|
||||||
throw new RuntimeException("Blank config property: canalInstances or canalKafkaTopics");
|
|
||||||
}
|
|
||||||
|
|
||||||
loader = ExtensionLoader.getExtensionLoader(CanalOuterAdapter.class,
|
|
||||||
"" /* TODO canalClientConfig.getClassloaderPolicy() */);
|
|
||||||
|
|
||||||
String canalServerHost = this.canalClientConfig.getCanalServerHost();
|
|
||||||
SocketAddress sa = null;
|
|
||||||
if (canalServerHost != null) {
|
|
||||||
String[] ipPort = canalServerHost.split(":");
|
|
||||||
sa = new InetSocketAddress(ipPort[0], Integer.parseInt(ipPort[1]));
|
|
||||||
}
|
|
||||||
String zkHosts = this.canalClientConfig.getZookeeperHosts();
|
|
||||||
|
|
||||||
// if (zkHosts == null && sa == null) {
|
|
||||||
// throw new RuntimeException("Blank config property: canalServerHost or
|
|
||||||
// zookeeperHosts");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// 初始化canal-client的适配器
|
|
||||||
if (canalClientConfig.getCanalInstances() != null) {
|
|
||||||
for (CanalClientConfig.CanalInstance instance : canalClientConfig.getCanalInstances()) {
|
|
||||||
List<List<CanalOuterAdapter>> canalOuterAdapterGroups = new ArrayList<>();
|
|
||||||
|
|
||||||
for (CanalClientConfig.AdapterGroup connectorGroup : instance.getAdapterGroups()) {
|
|
||||||
List<CanalOuterAdapter> canalOutConnectors = new ArrayList<>();
|
|
||||||
for (CanalOuterAdapterConfiguration c : connectorGroup.getOutAdapters()) {
|
|
||||||
loadConnector(c, canalOutConnectors);
|
|
||||||
}
|
|
||||||
canalOuterAdapterGroups.add(canalOutConnectors);
|
|
||||||
}
|
|
||||||
CanalAdapterWorker worker;
|
|
||||||
if (zkHosts != null) {
|
|
||||||
worker = new CanalAdapterWorker(instance.getInstance(), zkHosts, canalOuterAdapterGroups);
|
|
||||||
} else {
|
|
||||||
worker = new CanalAdapterWorker(instance.getInstance(), sa, canalOuterAdapterGroups);
|
|
||||||
}
|
|
||||||
canalWorkers.put(instance.getInstance(), worker);
|
|
||||||
worker.start();
|
|
||||||
logger.info("Start adapter for canal instance: {} succeed", instance.getInstance());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 初始化canal-client-kafka的适配器
|
|
||||||
if (canalClientConfig.getKafkaTopics() != null) {
|
|
||||||
for (CanalClientConfig.KafkaTopic kafkaTopic : canalClientConfig.getKafkaTopics()) {
|
|
||||||
for (CanalClientConfig.Group group : kafkaTopic.getGroups()) {
|
|
||||||
List<List<CanalOuterAdapter>> canalOuterAdapterGroups = new ArrayList<>();
|
|
||||||
|
|
||||||
List<CanalOuterAdapter> canalOuterAdapters = new ArrayList<>();
|
|
||||||
|
|
||||||
for (CanalOuterAdapterConfiguration config : group.getOutAdapters()) {
|
|
||||||
// for (CanalOuterAdapterConfiguration config : adaptor.getOutAdapters()) {
|
|
||||||
loadConnector(config, canalOuterAdapters);
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
canalOuterAdapterGroups.add(canalOuterAdapters);
|
|
||||||
|
|
||||||
// String zkServers = canalClientConfig.getZookeeperHosts();
|
|
||||||
CanalAdapterKafkaWorker canalKafkaWorker = new CanalAdapterKafkaWorker(zkHosts,
|
|
||||||
canalClientConfig.getBootstrapServers(),
|
|
||||||
kafkaTopic.getTopic(),
|
|
||||||
group.getGroupId(),
|
|
||||||
canalOuterAdapterGroups);
|
|
||||||
canalKafkaWorkers.put(kafkaTopic.getTopic() + "-" + group.getGroupId(), canalKafkaWorker);
|
|
||||||
canalKafkaWorker.start();
|
|
||||||
logger.info("Start adapter for canal-client kafka topic: {} succeed",
|
|
||||||
kafkaTopic.getTopic() + "-" + group.getGroupId());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void loadConnector(CanalOuterAdapterConfiguration config, List<CanalOuterAdapter> canalOutConnectors) {
|
|
||||||
try {
|
|
||||||
CanalOuterAdapter adapter = loader.getExtension(config.getName());
|
|
||||||
ClassLoader cl = Thread.currentThread().getContextClassLoader();
|
|
||||||
// 替换ClassLoader
|
|
||||||
Thread.currentThread().setContextClassLoader(adapter.getClass().getClassLoader());
|
|
||||||
adapter.init(config);
|
|
||||||
Thread.currentThread().setContextClassLoader(cl);
|
|
||||||
canalOutConnectors.add(adapter);
|
|
||||||
logger.info("Load canal adapter: {} succeed", config.getName());
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error("Load canal adapter: {} failed", config.getName(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 销毁所有适配器 为防止canal实例太多造成销毁阻塞, 并行销毁
|
|
||||||
*/
|
|
||||||
public void destroy() {
|
|
||||||
if (canalWorkers.size() > 0) {
|
|
||||||
ExecutorService stopExecutorService = Executors.newFixedThreadPool(canalWorkers.size());
|
|
||||||
for (CanalAdapterWorker v : canalWorkers.values()) {
|
|
||||||
final CanalAdapterWorker caw = v;
|
|
||||||
stopExecutorService.submit(new Runnable() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
caw.stop();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
stopExecutorService.shutdown();
|
|
||||||
}
|
|
||||||
if (canalKafkaWorkers.size() > 0) {
|
|
||||||
ExecutorService stopKafkaExecutorService = Executors.newFixedThreadPool(canalKafkaWorkers.size());
|
|
||||||
for (CanalAdapterKafkaWorker v : canalKafkaWorkers.values()) {
|
|
||||||
final CanalAdapterKafkaWorker cakw = v;
|
|
||||||
stopKafkaExecutorService.submit(new Runnable() {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
cakw.stop();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
stopKafkaExecutorService.shutdown();
|
|
||||||
}
|
|
||||||
logger.info("All canal adapters destroyed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
canalServerHost: 127.0.0.1:11111
|
|
||||||
#zookeeperHosts: slave1:2181
|
|
||||||
#bootstrapServers: slave1:6667,slave2:6667
|
|
||||||
|
|
||||||
canalInstances:
|
|
||||||
- instance: example
|
|
||||||
adapterGroups:
|
|
||||||
- outAdapters:
|
|
||||||
- name: logger
|
|
||||||
- name: hbase
|
|
||||||
hosts: slave1:2181
|
|
||||||
properties: {znodeParent: "/hbase-unsecure"}
|
|
||||||
#kafkaTopics:
|
|
||||||
#- topic: example
|
|
||||||
# groups:
|
|
||||||
# - groupId: example_g1
|
|
||||||
# outAdapters:
|
|
||||||
# - name: logger
|
|
||||||
# - name: hbase
|
|
||||||
# hosts: slave1:2181
|
|
||||||
# properties: {znodeParent: "/hbase-unsecure"}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
<configuration scan="true" scanPeriod=" 5 seconds">
|
|
||||||
<jmxConfigurator />
|
|
||||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{56} - %msg%n
|
|
||||||
</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<appender name="CANAL-ROOT" class="ch.qos.logback.classic.sift.SiftingAppender">
|
|
||||||
<discriminator>
|
|
||||||
<Key>destination</Key>
|
|
||||||
<DefaultValue>canal_client</DefaultValue>
|
|
||||||
</discriminator>
|
|
||||||
<sift>
|
|
||||||
<appender name="FILE-${destination}" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
|
||||||
<File>../logs/${destination}.log</File>
|
|
||||||
<rollingPolicy
|
|
||||||
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
|
||||||
<!-- rollover daily -->
|
|
||||||
<fileNamePattern>../logs/%d{yyyy-MM-dd}/${destination}-%d{yyyy-MM-dd}-%i.log.gz</fileNamePattern>
|
|
||||||
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
|
||||||
<!-- or whenever the file size reaches 100MB -->
|
|
||||||
<maxFileSize>512MB</maxFileSize>
|
|
||||||
</timeBasedFileNamingAndTriggeringPolicy>
|
|
||||||
<maxHistory>60</maxHistory>
|
|
||||||
</rollingPolicy>
|
|
||||||
<encoder>
|
|
||||||
<pattern>
|
|
||||||
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{56} - %msg%n
|
|
||||||
</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
</sift>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<logger name="com.alibaba.otter.canal.client" additivity="false">
|
|
||||||
<level value="INFO" />
|
|
||||||
<!--<appender-ref ref="STDOUT"/>-->
|
|
||||||
<appender-ref ref="CANAL-ROOT" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<root level="WARN">
|
|
||||||
<!--<appender-ref ref="STDOUT"/>-->
|
|
||||||
<appender-ref ref="CANAL-ROOT" />
|
|
||||||
</root>
|
|
||||||
</configuration>
|
|
||||||
162
client/pom.xml
162
client/pom.xml
@@ -3,7 +3,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<artifactId>canal</artifactId>
|
<artifactId>canal</artifactId>
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
<version>1.1.1</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
@@ -15,8 +15,100 @@
|
|||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<artifactId>canal.protocol</artifactId>
|
<artifactId>canal.protocol</artifactId>
|
||||||
<version>${project.version}</version>
|
<version>${project.version}</version>
|
||||||
|
<optional>true</optional>
|
||||||
</dependency>
|
</dependency>
|
||||||
<!-- 客户端要使用请单独引入kafka依赖 -->
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.protobuf</groupId>
|
||||||
|
<artifactId>protobuf-java</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.netty</groupId>
|
||||||
|
<artifactId>netty-all</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- zk -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.zookeeper</groupId>
|
||||||
|
<artifactId>zookeeper</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.101tec</groupId>
|
||||||
|
<artifactId>zkclient</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- external -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-io</groupId>
|
||||||
|
<artifactId>commons-io</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-lang</groupId>
|
||||||
|
<artifactId>commons-lang</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>commons-codec</groupId>
|
||||||
|
<artifactId>commons-codec</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba</groupId>
|
||||||
|
<artifactId>fastjson</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<!-- log -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-core</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>ch.qos.logback</groupId>
|
||||||
|
<artifactId>logback-classic</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>jcl-over-slf4j</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.slf4j</groupId>
|
||||||
|
<artifactId>slf4j-api</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-core</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-aop</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-context</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-jdbc</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-orm</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-test</artifactId>
|
||||||
|
<version>${spring_version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- 客户端要使用请单独引入rocketmq-client依赖 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.rocketmq</groupId>
|
||||||
|
<artifactId>rocketmq-client</artifactId>
|
||||||
|
<version>4.3.0</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- 客户端要使用请单独引入kafka-clients依赖 -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.kafka</groupId>
|
<groupId>org.apache.kafka</groupId>
|
||||||
<artifactId>kafka-clients</artifactId>
|
<artifactId>kafka-clients</artifactId>
|
||||||
@@ -28,9 +120,75 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
<artifactId>junit</artifactId>
|
<artifactId>junit</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-shade-plugin</artifactId>
|
||||||
|
<version>2.4.1</version>
|
||||||
|
<configuration>
|
||||||
|
<createDependencyReducedPom>false</createDependencyReducedPom>
|
||||||
|
<artifactSet>
|
||||||
|
<excludes>
|
||||||
|
<exclude>org.apache.zookeeper:zookeeper</exclude>
|
||||||
|
<exclude>com.101tec:zkclient</exclude>
|
||||||
|
<exclude>commons-io:commons-io</exclude>
|
||||||
|
<exclude>commons-lang:commons-lang</exclude>
|
||||||
|
<exclude>commons-codec:commons-codec</exclude>
|
||||||
|
<exclude>com.alibaba:fastjson</exclude>
|
||||||
|
<exclude>ch.qos.logback:logback-core</exclude>
|
||||||
|
<exclude>ch.qos.logback:logback-classic</exclude>
|
||||||
|
<exclude>org.slf4j:jcl-over-slf4j</exclude>
|
||||||
|
<exclude>org.slf4j:slf4j-api</exclude>
|
||||||
|
<exclude>org.springframework:*</exclude>
|
||||||
|
<exclude>org.jboss.netty:netty</exclude>
|
||||||
|
<exclude>commons-logging:commons-logging</exclude>
|
||||||
|
<exclude>aopalliance:aopalliance</exclude>
|
||||||
|
<exclude>com.google.protobuf:protobuf-java</exclude>
|
||||||
|
<exclude>io.netty:*</exclude>
|
||||||
|
<exclude>junit:junit</exclude>
|
||||||
|
</excludes>
|
||||||
|
</artifactSet>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>shade</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<relocations>
|
||||||
|
<relocation>
|
||||||
|
<pattern>com.google.guava</pattern>
|
||||||
|
<shadedPattern>com.alibaba.google.guava</shadedPattern>
|
||||||
|
</relocation>
|
||||||
|
<relocation>
|
||||||
|
<pattern>org.joda</pattern>
|
||||||
|
<shadedPattern>com.alibaba.google.joda</shadedPattern>
|
||||||
|
</relocation>
|
||||||
|
<relocation>
|
||||||
|
<pattern>com.google.common</pattern>
|
||||||
|
<shadedPattern>com.alibaba.google.common</shadedPattern>
|
||||||
|
</relocation>
|
||||||
|
<relocation>
|
||||||
|
<pattern>com.google.thirdparty</pattern>
|
||||||
|
<shadedPattern>com.alibaba.google.thirdparty</shadedPattern>
|
||||||
|
</relocation>
|
||||||
|
</relocations>
|
||||||
|
<transformers>
|
||||||
|
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer" />
|
||||||
|
</transformers>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
<profiles>
|
<profiles>
|
||||||
<profile>
|
<profile>
|
||||||
<id>dev</id>
|
<id>dev</id>
|
||||||
|
|||||||
@@ -149,11 +149,4 @@ public interface CanalConnector {
|
|||||||
* @throws CanalClientException
|
* @throws CanalClientException
|
||||||
*/
|
*/
|
||||||
void rollback() throws CanalClientException;
|
void rollback() throws CanalClientException;
|
||||||
|
|
||||||
/**
|
|
||||||
* 中断的阻塞,用于优雅停止client
|
|
||||||
*
|
|
||||||
* @throws CanalClientException
|
|
||||||
*/
|
|
||||||
void stopRunning() throws CanalClientException;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package com.alibaba.otter.canal.client;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.protocol.FlatMessage;
|
||||||
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* canal MQ数据操作客户端
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* 1. canal server写入MQ消息,考虑性能会合并多条数据写入为一个MQ消息,一个Message对应一个MQ消息
|
||||||
|
* 2. canal client消费MQ消息,因为client性能会弱于server的写入,MQ数据获取时会拿到堆积的多条MQ消息,会拿到List<Message>
|
||||||
|
* 3. client的ack/rollback,都是和MQ直接交互,不存在对应的batchId概念
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @author agapple 2018年10月28日 下午6:42:27
|
||||||
|
* @since 1.1.1
|
||||||
|
*/
|
||||||
|
public interface CanalMQConnector extends CanalConnector {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取数据,自动进行确认,设置timeout时间直到拿到数据为止
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* 该方法返回的条件:
|
||||||
|
* a. 如果timeout=0,有多少取多少,不会阻塞等待
|
||||||
|
* b. 如果timeout不为0,尝试阻塞对应的超时时间,直到拿到数据就返回
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
* @throws CanalClientException
|
||||||
|
*/
|
||||||
|
List<Message> getList(Long timeout, TimeUnit unit) throws CanalClientException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取数据,设置timeout时间直到拿到数据为止
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* 该方法返回的条件:
|
||||||
|
* a. 如果timeout=0,有多少取多少,不会阻塞等待
|
||||||
|
* b. 如果timeout不为0,尝试阻塞对应的超时时间,直到拿到数据就返回
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @throws CanalClientException
|
||||||
|
*/
|
||||||
|
List<Message> getListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取数据,自动进行确认,设置timeout时间直到拿到数据为止
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* 该方法返回的条件:
|
||||||
|
* a. 如果timeout=0,有多少取多少,不会阻塞等待
|
||||||
|
* b. 如果timeout不为0,尝试阻塞对应的超时时间,直到拿到数据就返回
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
* @throws CanalClientException
|
||||||
|
*/
|
||||||
|
List<FlatMessage> getFlatList(Long timeout, TimeUnit unit) throws CanalClientException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取数据,设置timeout时间直到拿到数据为止
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* 该方法返回的条件:
|
||||||
|
* a. 如果timeout=0,有多少取多少,不会阻塞等待
|
||||||
|
* b. 如果timeout不为0,尝试阻塞对应的超时时间,直到拿到数据就返回
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @throws CanalClientException
|
||||||
|
*/
|
||||||
|
List<FlatMessage> getFlatListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 消费确认。
|
||||||
|
*
|
||||||
|
* @throws CanalClientException
|
||||||
|
*/
|
||||||
|
void ack() throws CanalClientException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 回滚到未进行 {@link #ack} 的地方,下次fetch的时候,可以从最后一个没有 {@link #ack} 的地方开始拿
|
||||||
|
*
|
||||||
|
* @throws CanalClientException
|
||||||
|
*/
|
||||||
|
void rollback() throws CanalClientException;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package com.alibaba.otter.canal.client;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.protocol.CanalEntry;
|
||||||
|
import com.alibaba.otter.canal.protocol.CanalPacket;
|
||||||
|
import com.alibaba.otter.canal.protocol.CanalPacket.Ack;
|
||||||
|
import com.alibaba.otter.canal.protocol.CanalPacket.Compression;
|
||||||
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
|
||||||
|
import com.google.protobuf.ByteString;
|
||||||
|
|
||||||
|
public class CanalMessageDeserializer {
|
||||||
|
|
||||||
|
public static Message deserializer(byte[] data) {
|
||||||
|
return deserializer(data, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Message deserializer(byte[] data, boolean lazyParseEntry) {
|
||||||
|
try {
|
||||||
|
if (data == null) {
|
||||||
|
return null;
|
||||||
|
} else {
|
||||||
|
CanalPacket.Packet p = CanalPacket.Packet.parseFrom(data);
|
||||||
|
switch (p.getType()) {
|
||||||
|
case MESSAGES: {
|
||||||
|
if (!p.getCompression().equals(Compression.NONE)
|
||||||
|
&& !p.getCompression().equals(Compression.COMPRESSIONCOMPATIBLEPROTO2)) {
|
||||||
|
throw new CanalClientException("compression is not supported in this connector");
|
||||||
|
}
|
||||||
|
|
||||||
|
CanalPacket.Messages messages = CanalPacket.Messages.parseFrom(p.getBody());
|
||||||
|
Message result = new Message(messages.getBatchId());
|
||||||
|
if (lazyParseEntry) {
|
||||||
|
// byteString
|
||||||
|
result.setRawEntries(messages.getMessagesList());
|
||||||
|
} else {
|
||||||
|
for (ByteString byteString : messages.getMessagesList()) {
|
||||||
|
result.addEntry(CanalEntry.Entry.parseFrom(byteString));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
case ACK: {
|
||||||
|
Ack ack = Ack.parseFrom(p.getBody());
|
||||||
|
throw new CanalClientException("something goes wrong with reason: " + ack.getErrorMessage());
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
throw new CanalClientException("unexpected packet type: " + p.getType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new CanalClientException("deserializer failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -218,8 +218,7 @@ public class ClusterCanalConnector implements CanalConnector {
|
|||||||
return;
|
return;
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
logger.warn(String.format("something goes wrong when rollbacking data from server:%s",
|
logger.warn(String.format("something goes wrong when rollbacking data from server:%s",
|
||||||
currentConnector != null ? currentConnector.getAddress() : "null"),
|
currentConnector != null ? currentConnector.getAddress() : "null"), t);
|
||||||
t);
|
|
||||||
times++;
|
times++;
|
||||||
restart();
|
restart();
|
||||||
logger.info("restart the connector for next round retry.");
|
logger.info("restart the connector for next round retry.");
|
||||||
@@ -236,8 +235,7 @@ public class ClusterCanalConnector implements CanalConnector {
|
|||||||
return;
|
return;
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
logger.warn(String.format("something goes wrong when rollbacking data from server:%s",
|
logger.warn(String.format("something goes wrong when rollbacking data from server:%s",
|
||||||
currentConnector != null ? currentConnector.getAddress() : "null"),
|
currentConnector != null ? currentConnector.getAddress() : "null"), t);
|
||||||
t);
|
|
||||||
times++;
|
times++;
|
||||||
restart();
|
restart();
|
||||||
logger.info("restart the connector for next round retry.");
|
logger.info("restart the connector for next round retry.");
|
||||||
@@ -255,8 +253,7 @@ public class ClusterCanalConnector implements CanalConnector {
|
|||||||
return;
|
return;
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
logger.warn(String.format("something goes wrong when acking data from server:%s",
|
logger.warn(String.format("something goes wrong when acking data from server:%s",
|
||||||
currentConnector != null ? currentConnector.getAddress() : "null"),
|
currentConnector != null ? currentConnector.getAddress() : "null"), t);
|
||||||
t);
|
|
||||||
times++;
|
times++;
|
||||||
restart();
|
restart();
|
||||||
logger.info("restart the connector for next round retry.");
|
logger.info("restart the connector for next round retry.");
|
||||||
|
|||||||
@@ -18,13 +18,13 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.CanalConnector;
|
import com.alibaba.otter.canal.client.CanalConnector;
|
||||||
|
import com.alibaba.otter.canal.client.CanalMessageDeserializer;
|
||||||
import com.alibaba.otter.canal.client.impl.running.ClientRunningData;
|
import com.alibaba.otter.canal.client.impl.running.ClientRunningData;
|
||||||
import com.alibaba.otter.canal.client.impl.running.ClientRunningListener;
|
import com.alibaba.otter.canal.client.impl.running.ClientRunningListener;
|
||||||
import com.alibaba.otter.canal.client.impl.running.ClientRunningMonitor;
|
import com.alibaba.otter.canal.client.impl.running.ClientRunningMonitor;
|
||||||
import com.alibaba.otter.canal.common.utils.AddressUtils;
|
import com.alibaba.otter.canal.common.utils.AddressUtils;
|
||||||
import com.alibaba.otter.canal.common.utils.BooleanMutex;
|
import com.alibaba.otter.canal.common.utils.BooleanMutex;
|
||||||
import com.alibaba.otter.canal.common.zookeeper.ZkClientx;
|
import com.alibaba.otter.canal.common.zookeeper.ZkClientx;
|
||||||
import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
|
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.Ack;
|
import com.alibaba.otter.canal.protocol.CanalPacket.Ack;
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.ClientAck;
|
import com.alibaba.otter.canal.protocol.CanalPacket.ClientAck;
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.ClientAuth;
|
import com.alibaba.otter.canal.protocol.CanalPacket.ClientAuth;
|
||||||
@@ -32,7 +32,6 @@ import com.alibaba.otter.canal.protocol.CanalPacket.ClientRollback;
|
|||||||
import com.alibaba.otter.canal.protocol.CanalPacket.Compression;
|
import com.alibaba.otter.canal.protocol.CanalPacket.Compression;
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.Get;
|
import com.alibaba.otter.canal.protocol.CanalPacket.Get;
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.Handshake;
|
import com.alibaba.otter.canal.protocol.CanalPacket.Handshake;
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.Messages;
|
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.Packet;
|
import com.alibaba.otter.canal.protocol.CanalPacket.Packet;
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.PacketType;
|
import com.alibaba.otter.canal.protocol.CanalPacket.PacketType;
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket.Sub;
|
import com.alibaba.otter.canal.protocol.CanalPacket.Sub;
|
||||||
@@ -159,7 +158,7 @@ public class SimpleCanalConnector implements CanalConnector {
|
|||||||
}
|
}
|
||||||
//
|
//
|
||||||
Handshake handshake = Handshake.parseFrom(p.getBody());
|
Handshake handshake = Handshake.parseFrom(p.getBody());
|
||||||
supportedCompressions.addAll(handshake.getSupportedCompressionsList());
|
supportedCompressions.add(handshake.getSupportedCompressions());
|
||||||
//
|
//
|
||||||
ClientAuth ca = ClientAuth.newBuilder()
|
ClientAuth ca = ClientAuth.newBuilder()
|
||||||
.setUsername(username != null ? username : "")
|
.setUsername(username != null ? username : "")
|
||||||
@@ -320,33 +319,7 @@ public class SimpleCanalConnector implements CanalConnector {
|
|||||||
|
|
||||||
private Message receiveMessages() throws IOException {
|
private Message receiveMessages() throws IOException {
|
||||||
byte[] data = readNextPacket();
|
byte[] data = readNextPacket();
|
||||||
Packet p = Packet.parseFrom(data);
|
return CanalMessageDeserializer.deserializer(data, lazyParseEntry);
|
||||||
switch (p.getType()) {
|
|
||||||
case MESSAGES: {
|
|
||||||
if (!p.getCompression().equals(Compression.NONE)) {
|
|
||||||
throw new CanalClientException("compression is not supported in this connector");
|
|
||||||
}
|
|
||||||
|
|
||||||
Messages messages = Messages.parseFrom(p.getBody());
|
|
||||||
Message result = new Message(messages.getBatchId());
|
|
||||||
if (lazyParseEntry) {
|
|
||||||
// byteString
|
|
||||||
result.setRawEntries(messages.getMessagesList());
|
|
||||||
} else {
|
|
||||||
for (ByteString byteString : messages.getMessagesList()) {
|
|
||||||
result.addEntry(Entry.parseFrom(byteString));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
case ACK: {
|
|
||||||
Ack ack = Ack.parseFrom(p.getBody());
|
|
||||||
throw new CanalClientException("something goes wrong with reason: " + ack.getErrorMessage());
|
|
||||||
}
|
|
||||||
default: {
|
|
||||||
throw new CanalClientException("unexpected packet type: " + p.getType());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ack(long batchId) throws CanalClientException {
|
public void ack(long batchId) throws CanalClientException {
|
||||||
|
|||||||
@@ -1,41 +1,51 @@
|
|||||||
package com.alibaba.otter.canal.client.kafka;
|
package com.alibaba.otter.canal.client.kafka;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||||
import org.apache.kafka.common.TopicPartition;
|
import org.apache.kafka.common.TopicPartition;
|
||||||
import org.apache.kafka.common.serialization.StringDeserializer;
|
import org.apache.kafka.common.serialization.StringDeserializer;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.client.kafka.running.ClientRunningData;
|
import com.alibaba.fastjson.JSON;
|
||||||
import com.alibaba.otter.canal.common.utils.AddressUtils;
|
import com.alibaba.otter.canal.client.CanalMQConnector;
|
||||||
import com.alibaba.otter.canal.common.zookeeper.ZkClientx;
|
import com.alibaba.otter.canal.client.impl.SimpleCanalConnector;
|
||||||
|
import com.alibaba.otter.canal.protocol.FlatMessage;
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
|
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* canal kafka 数据操作客户端
|
* canal kafka 数据操作客户端
|
||||||
*
|
*
|
||||||
|
* <pre>
|
||||||
|
* 注意点:
|
||||||
|
* 1. 相比于canal {@linkplain SimpleCanalConnector}, 这里get和ack操作不能有并发, 必须是一个线程执行get后,内存里执行完毕ack后再取下一个get
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
* @author machengyuan @ 2018-6-12
|
* @author machengyuan @ 2018-6-12
|
||||||
* @version 1.0.0
|
* @version 1.1.1
|
||||||
*/
|
*/
|
||||||
public class KafkaCanalConnector {
|
public class KafkaCanalConnector implements CanalMQConnector {
|
||||||
|
|
||||||
private KafkaConsumer<String, Message> kafkaConsumer;
|
private KafkaConsumer<String, Message> kafkaConsumer;
|
||||||
|
private KafkaConsumer<String, String> kafkaConsumer2; // 用于扁平message的数据消费
|
||||||
private String topic;
|
private String topic;
|
||||||
private Integer partition;
|
private Integer partition;
|
||||||
private Properties properties;
|
private Properties properties;
|
||||||
// private ClientRunningMonitor runningMonitor; // 运行控制
|
|
||||||
// private BooleanMutex mutex = new BooleanMutex(false);
|
|
||||||
private ZkClientx zkClientx;
|
|
||||||
private volatile boolean connected = false;
|
private volatile boolean connected = false;
|
||||||
private volatile boolean running = false;
|
private volatile boolean running = false;
|
||||||
|
private boolean flatMessage;
|
||||||
|
|
||||||
public KafkaCanalConnector(String zkServers, String servers, String topic, Integer partition, String groupId){
|
public KafkaCanalConnector(String servers, String topic, Integer partition, String groupId, boolean flatMessage){
|
||||||
this.topic = topic;
|
this.topic = topic;
|
||||||
this.partition = partition;
|
this.partition = partition;
|
||||||
|
this.flatMessage = flatMessage;
|
||||||
|
|
||||||
properties = new Properties();
|
properties = new Properties();
|
||||||
properties.put("bootstrap.servers", servers);
|
properties.put("bootstrap.servers", servers);
|
||||||
@@ -45,32 +55,222 @@ public class KafkaCanalConnector {
|
|||||||
properties.put("auto.offset.reset", "latest"); // 如果没有offset则从最后的offset开始读
|
properties.put("auto.offset.reset", "latest"); // 如果没有offset则从最后的offset开始读
|
||||||
properties.put("request.timeout.ms", "40000"); // 必须大于session.timeout.ms的设置
|
properties.put("request.timeout.ms", "40000"); // 必须大于session.timeout.ms的设置
|
||||||
properties.put("session.timeout.ms", "30000"); // 默认为30秒
|
properties.put("session.timeout.ms", "30000"); // 默认为30秒
|
||||||
properties.put("max.poll.records", "1"); // 一次只取一条message数据
|
properties.put("max.poll.records", "100");
|
||||||
properties.put("key.deserializer", StringDeserializer.class.getName());
|
properties.put("key.deserializer", StringDeserializer.class.getName());
|
||||||
|
if (!flatMessage) {
|
||||||
properties.put("value.deserializer", MessageDeserializer.class.getName());
|
properties.put("value.deserializer", MessageDeserializer.class.getName());
|
||||||
|
} else {
|
||||||
if (zkServers != null) {
|
properties.put("value.deserializer", StringDeserializer.class.getName());
|
||||||
zkClientx = new ZkClientx(zkServers);
|
}
|
||||||
|
|
||||||
ClientRunningData clientData = new ClientRunningData();
|
|
||||||
clientData.setGroupId(groupId);
|
|
||||||
clientData.setAddress(AddressUtils.getHostIp());
|
|
||||||
|
|
||||||
// runningMonitor = new ClientRunningMonitor();
|
|
||||||
// runningMonitor.setTopic(topic);
|
|
||||||
// runningMonitor.setZkClient(zkClientx);
|
|
||||||
// runningMonitor.setClientData(clientData);
|
|
||||||
// runningMonitor.setListener(new ClientRunningListener() {
|
|
||||||
// public void processActiveEnter() {
|
|
||||||
// mutex.set(true);
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// public void processActiveExit() {
|
|
||||||
// mutex.set(false);
|
|
||||||
// }
|
|
||||||
// });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开连接
|
||||||
|
*/
|
||||||
|
public void connect() {
|
||||||
|
if (connected) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
connected = true;
|
||||||
|
if (kafkaConsumer == null && !flatMessage) {
|
||||||
|
kafkaConsumer = new KafkaConsumer<String, Message>(properties);
|
||||||
|
}
|
||||||
|
if (kafkaConsumer2 == null && flatMessage) {
|
||||||
|
kafkaConsumer2 = new KafkaConsumer<String, String>(properties);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭链接
|
||||||
|
*/
|
||||||
|
public void disconnect() {
|
||||||
|
if (kafkaConsumer != null) {
|
||||||
|
kafkaConsumer.close();
|
||||||
|
kafkaConsumer = null;
|
||||||
|
}
|
||||||
|
if (kafkaConsumer2 != null) {
|
||||||
|
kafkaConsumer2.close();
|
||||||
|
kafkaConsumer2 = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
connected = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void waitClientRunning() {
|
||||||
|
running = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean checkValid() {
|
||||||
|
return true;// 默认都放过
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订阅topic
|
||||||
|
*/
|
||||||
|
public void subscribe() {
|
||||||
|
waitClientRunning();
|
||||||
|
if (!running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (partition == null) {
|
||||||
|
if (kafkaConsumer != null) {
|
||||||
|
kafkaConsumer.subscribe(Collections.singletonList(topic));
|
||||||
|
}
|
||||||
|
if (kafkaConsumer2 != null) {
|
||||||
|
kafkaConsumer2.subscribe(Collections.singletonList(topic));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
TopicPartition topicPartition = new TopicPartition(topic, partition);
|
||||||
|
if (kafkaConsumer != null) {
|
||||||
|
kafkaConsumer.assign(Collections.singletonList(topicPartition));
|
||||||
|
}
|
||||||
|
if (kafkaConsumer2 != null) {
|
||||||
|
kafkaConsumer2.assign(Collections.singletonList(topicPartition));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消订阅
|
||||||
|
*/
|
||||||
|
public void unsubscribe() {
|
||||||
|
waitClientRunning();
|
||||||
|
if (!running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kafkaConsumer != null) {
|
||||||
|
kafkaConsumer.unsubscribe();
|
||||||
|
}
|
||||||
|
if (kafkaConsumer2 != null) {
|
||||||
|
kafkaConsumer2.unsubscribe();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Message> getList(Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
waitClientRunning();
|
||||||
|
if (!running) {
|
||||||
|
return Lists.newArrayList();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Message> messages = getListWithoutAck(timeout, unit);
|
||||||
|
if (messages != null && !messages.isEmpty()) {
|
||||||
|
this.ack();
|
||||||
|
}
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Message> getListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
waitClientRunning();
|
||||||
|
if (!running) {
|
||||||
|
return Lists.newArrayList();
|
||||||
|
}
|
||||||
|
|
||||||
|
ConsumerRecords<String, Message> records = kafkaConsumer.poll(unit.toMillis(timeout)); // 基于配置,最多只能poll到一条数据
|
||||||
|
|
||||||
|
if (!records.isEmpty()) {
|
||||||
|
List<Message> messages = new ArrayList<>();
|
||||||
|
for (ConsumerRecord<String, Message> record : records) {
|
||||||
|
messages.add(record.value());
|
||||||
|
}
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
return Lists.newArrayList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FlatMessage> getFlatList(Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
waitClientRunning();
|
||||||
|
if (!running) {
|
||||||
|
return Lists.newArrayList();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<FlatMessage> messages = getFlatListWithoutAck(timeout, unit);
|
||||||
|
if (messages != null && !messages.isEmpty()) {
|
||||||
|
this.ack();
|
||||||
|
}
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FlatMessage> getFlatListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
waitClientRunning();
|
||||||
|
if (!running) {
|
||||||
|
return Lists.newArrayList();
|
||||||
|
}
|
||||||
|
|
||||||
|
ConsumerRecords<String, String> records = kafkaConsumer2.poll(unit.toMillis(timeout));
|
||||||
|
if (!records.isEmpty()) {
|
||||||
|
List<FlatMessage> flatMessages = new ArrayList<>();
|
||||||
|
for (ConsumerRecord<String, String> record : records) {
|
||||||
|
String flatMessageJson = record.value();
|
||||||
|
FlatMessage flatMessage = JSON.parseObject(flatMessageJson, FlatMessage.class);
|
||||||
|
flatMessages.add(flatMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
return flatMessages;
|
||||||
|
}
|
||||||
|
return Lists.newArrayList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void rollback() throws CanalClientException {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交offset,如果超过 session.timeout.ms 设置的时间没有ack则会抛出异常,ack失败
|
||||||
|
*/
|
||||||
|
public void ack() {
|
||||||
|
waitClientRunning();
|
||||||
|
if (!running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kafkaConsumer != null) {
|
||||||
|
kafkaConsumer.commitSync();
|
||||||
|
}
|
||||||
|
if (kafkaConsumer2 != null) {
|
||||||
|
kafkaConsumer2.commitSync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void subscribe(String filter) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Message get(int batchSize) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Message get(int batchSize, Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Message getWithoutAck(int batchSize) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Message getWithoutAck(int batchSize, Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void ack(long batchId) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void rollback(long batchId) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -85,157 +285,4 @@ public class KafkaCanalConnector {
|
|||||||
properties.put("session.timeout.ms", String.valueOf(t));
|
properties.put("session.timeout.ms", String.valueOf(t));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 打开连接
|
|
||||||
*/
|
|
||||||
public void connect() {
|
|
||||||
if (connected) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// if (runningMonitor != null) {
|
|
||||||
// if (!runningMonitor.isStart()) {
|
|
||||||
// runningMonitor.start();
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
connected = true;
|
|
||||||
|
|
||||||
if (kafkaConsumer == null) {
|
|
||||||
kafkaConsumer = new KafkaConsumer<String, Message>(properties);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 关闭链接
|
|
||||||
*/
|
|
||||||
public void disconnnect() {
|
|
||||||
kafkaConsumer.close();
|
|
||||||
|
|
||||||
connected = false;
|
|
||||||
// if (runningMonitor.isStart()) {
|
|
||||||
// runningMonitor.stop();
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
|
|
||||||
private void waitClientRunning() {
|
|
||||||
try {
|
|
||||||
if (zkClientx != null) {
|
|
||||||
if (!connected) {// 未调用connect
|
|
||||||
throw new CanalClientException("should connect first");
|
|
||||||
}
|
|
||||||
|
|
||||||
running = true;
|
|
||||||
// mutex.get();// 阻塞等待
|
|
||||||
} else {
|
|
||||||
// 单机模式直接设置为running
|
|
||||||
running = true;
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
Thread.currentThread().interrupt();
|
|
||||||
throw new CanalClientException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean checkValid() {
|
|
||||||
if (zkClientx != null) {
|
|
||||||
// return mutex.state();
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
return true;// 默认都放过
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 订阅topic
|
|
||||||
*/
|
|
||||||
public void subscribe() {
|
|
||||||
waitClientRunning();
|
|
||||||
if (!running) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (partition == null) {
|
|
||||||
kafkaConsumer.subscribe(Collections.singletonList(topic));
|
|
||||||
} else {
|
|
||||||
TopicPartition topicPartition = new TopicPartition(topic, partition);
|
|
||||||
kafkaConsumer.assign(Collections.singletonList(topicPartition));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 取消订阅
|
|
||||||
*/
|
|
||||||
public void unsubscribe() {
|
|
||||||
waitClientRunning();
|
|
||||||
if (!running) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
kafkaConsumer.unsubscribe();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取数据,自动进行确认
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public Message get() {
|
|
||||||
return get(100L, TimeUnit.MILLISECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Message get(Long timeout, TimeUnit unit) {
|
|
||||||
waitClientRunning();
|
|
||||||
if (!running) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
Message message = getWithoutAck(timeout, unit);
|
|
||||||
this.ack();
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Message getWithoutAck() {
|
|
||||||
return getWithoutAck(100L, TimeUnit.MILLISECONDS);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取数据,不进行确认,等待处理完成手工确认
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public Message getWithoutAck(Long timeout, TimeUnit unit) {
|
|
||||||
waitClientRunning();
|
|
||||||
if (!running) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
ConsumerRecords<String, Message> records = kafkaConsumer.poll(unit.toMillis(timeout)); // 基于配置,最多只能poll到一条数据
|
|
||||||
|
|
||||||
if (!records.isEmpty()) {
|
|
||||||
return records.iterator().next().value();
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 提交offset,如果超过 session.timeout.ms 设置的时间没有ack则会抛出异常,ack失败
|
|
||||||
*/
|
|
||||||
public void ack() {
|
|
||||||
waitClientRunning();
|
|
||||||
if (!running) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
kafkaConsumer.commitSync();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stopRunning() {
|
|
||||||
if (running) {
|
|
||||||
running = false; // 设置为非running状态
|
|
||||||
// if (!mutex.state()) {
|
|
||||||
// mutex.set(true); // 中断阻塞
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ public class KafkaCanalConnectors {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public static KafkaCanalConnector newKafkaConnector(String servers, String topic, Integer partition, String groupId) {
|
public static KafkaCanalConnector newKafkaConnector(String servers, String topic, Integer partition, String groupId) {
|
||||||
return new KafkaCanalConnector(null, servers, topic, partition, groupId);
|
return new KafkaCanalConnector(servers, topic, partition, groupId, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -30,33 +30,21 @@ public class KafkaCanalConnectors {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public static KafkaCanalConnector newKafkaConnector(String servers, String topic, String groupId) {
|
public static KafkaCanalConnector newKafkaConnector(String servers, String topic, String groupId) {
|
||||||
return new KafkaCanalConnector(null, servers, topic, null, groupId);
|
return new KafkaCanalConnector(servers, topic, null, groupId, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建kafka客户端链接
|
* 创建kafka客户端链接
|
||||||
*
|
*
|
||||||
* @param zkServers
|
|
||||||
* @param servers
|
* @param servers
|
||||||
* @param topic
|
* @param topic
|
||||||
* @param partition
|
* @param partition
|
||||||
* @param groupId
|
* @param groupId
|
||||||
|
* @param flatMessage
|
||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
public static KafkaCanalConnector newKafkaConnector(String zkServers, String servers, String topic, Integer partition, String groupId) {
|
public static KafkaCanalConnector newKafkaConnector(String servers, String topic, Integer partition,
|
||||||
return new KafkaCanalConnector(zkServers, servers, topic, partition, groupId);
|
String groupId, boolean flatMessage) {
|
||||||
}
|
return new KafkaCanalConnector(servers, topic, partition, groupId, flatMessage);
|
||||||
|
|
||||||
/**
|
|
||||||
* 创建kafka客户端链接
|
|
||||||
*
|
|
||||||
* @param zkServers
|
|
||||||
* @param servers
|
|
||||||
* @param topic
|
|
||||||
* @param groupId
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public static KafkaCanalConnector newKafkaConnector(String zkServers, String servers, String topic, String groupId) {
|
|
||||||
return new KafkaCanalConnector(zkServers, servers, topic, null, groupId);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,9 @@ package com.alibaba.otter.canal.client.kafka;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import org.apache.kafka.common.serialization.Deserializer;
|
import org.apache.kafka.common.serialization.Deserializer;
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.protocol.CanalEntry;
|
import com.alibaba.otter.canal.client.CanalMessageDeserializer;
|
||||||
import com.alibaba.otter.canal.protocol.CanalPacket;
|
|
||||||
import com.alibaba.otter.canal.protocol.Message;
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
|
|
||||||
import com.google.protobuf.ByteString;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Kafka Message类的反序列化
|
* Kafka Message类的反序列化
|
||||||
@@ -20,41 +15,13 @@ import com.google.protobuf.ByteString;
|
|||||||
*/
|
*/
|
||||||
public class MessageDeserializer implements Deserializer<Message> {
|
public class MessageDeserializer implements Deserializer<Message> {
|
||||||
|
|
||||||
private static Logger logger = LoggerFactory.getLogger(MessageDeserializer.class);
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void configure(Map<String, ?> configs, boolean isKey) {
|
public void configure(Map<String, ?> configs, boolean isKey) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Message deserialize(String topic, byte[] data) {
|
public Message deserialize(String topic1, byte[] data) {
|
||||||
try {
|
return CanalMessageDeserializer.deserializer(data);
|
||||||
if (data == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
CanalPacket.Packet p = CanalPacket.Packet.parseFrom(data);
|
|
||||||
switch (p.getType()) {
|
|
||||||
case MESSAGES: {
|
|
||||||
if (!p.getCompression().equals(CanalPacket.Compression.NONE)) {
|
|
||||||
throw new CanalClientException("compression is not supported in this connector");
|
|
||||||
}
|
|
||||||
|
|
||||||
CanalPacket.Messages messages = CanalPacket.Messages.parseFrom(p.getBody());
|
|
||||||
Message result = new Message(messages.getBatchId());
|
|
||||||
for (ByteString byteString : messages.getMessagesList()) {
|
|
||||||
result.addEntry(CanalEntry.Entry.parseFrom(byteString));
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error("Error when deserializing byte[] to message ");
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.kafka.running;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* client running状态信息
|
|
||||||
*
|
|
||||||
* @author machengyuan 2018-06-20 下午04:10:12
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
public class ClientRunningData {
|
|
||||||
|
|
||||||
private String groupId;
|
|
||||||
private String address;
|
|
||||||
private boolean active = true;
|
|
||||||
|
|
||||||
public String getGroupId() {
|
|
||||||
return groupId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setGroupId(String groupId) {
|
|
||||||
this.groupId = groupId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAddress() {
|
|
||||||
return address;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAddress(String address) {
|
|
||||||
this.address = address;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isActive() {
|
|
||||||
return active;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setActive(boolean active) {
|
|
||||||
this.active = active;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.kafka.running;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* client running状态信息
|
|
||||||
*
|
|
||||||
* @author machengyuan 2018-06-20 下午04:10:12
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
public interface ClientRunningListener {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 触发现在轮到自己做为active
|
|
||||||
*/
|
|
||||||
public void processActiveEnter();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 触发一下当前active模式失败
|
|
||||||
*/
|
|
||||||
public void processActiveExit();
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,281 +0,0 @@
|
|||||||
package com.alibaba.otter.canal.client.kafka.running;
|
|
||||||
|
|
||||||
import java.text.MessageFormat;
|
|
||||||
import java.util.Random;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import org.I0Itec.zkclient.IZkDataListener;
|
|
||||||
import org.I0Itec.zkclient.exception.ZkException;
|
|
||||||
import org.I0Itec.zkclient.exception.ZkInterruptedException;
|
|
||||||
import org.I0Itec.zkclient.exception.ZkNoNodeException;
|
|
||||||
import org.I0Itec.zkclient.exception.ZkNodeExistsException;
|
|
||||||
import org.apache.zookeeper.CreateMode;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.slf4j.MDC;
|
|
||||||
|
|
||||||
import com.alibaba.otter.canal.common.AbstractCanalLifeCycle;
|
|
||||||
import com.alibaba.otter.canal.common.utils.AddressUtils;
|
|
||||||
import com.alibaba.otter.canal.common.utils.BooleanMutex;
|
|
||||||
import com.alibaba.otter.canal.common.utils.JsonUtils;
|
|
||||||
import com.alibaba.otter.canal.common.zookeeper.ZkClientx;
|
|
||||||
import com.alibaba.otter.canal.common.zookeeper.ZookeeperPathUtils;
|
|
||||||
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* kafka client running状态信息
|
|
||||||
*
|
|
||||||
* @author machengyuan 2018-06-20 下午04:10:12
|
|
||||||
* @version 1.0.0
|
|
||||||
*/
|
|
||||||
public class ClientRunningMonitor extends AbstractCanalLifeCycle {
|
|
||||||
|
|
||||||
private static final String TOPIC_ROOT_NODE = ZookeeperPathUtils.CANAL_ROOT_NODE
|
|
||||||
+ ZookeeperPathUtils.ZOOKEEPER_SEPARATOR + "topics";
|
|
||||||
|
|
||||||
private static final String TOPIC_NODE = TOPIC_ROOT_NODE + ZookeeperPathUtils.ZOOKEEPER_SEPARATOR
|
|
||||||
+ "{0}";
|
|
||||||
|
|
||||||
private static final String TOPIC_CLIENTID_NODE = TOPIC_NODE + ZookeeperPathUtils.ZOOKEEPER_SEPARATOR
|
|
||||||
+ "{1}";
|
|
||||||
|
|
||||||
private static final String TOPIC_CLIENTID_RUNNING_NODE = TOPIC_CLIENTID_NODE
|
|
||||||
+ ZookeeperPathUtils.ZOOKEEPER_SEPARATOR
|
|
||||||
+ ZookeeperPathUtils.RUNNING_NODE;
|
|
||||||
|
|
||||||
private static String getTopicClientRunning(String topic, String groupId) {
|
|
||||||
return MessageFormat.format(TOPIC_CLIENTID_RUNNING_NODE, topic, groupId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String getClientIdNodePath(String topic, String groupId) {
|
|
||||||
return MessageFormat.format(TOPIC_CLIENTID_NODE, topic, groupId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(ClientRunningMonitor.class);
|
|
||||||
private ZkClientx zkClient;
|
|
||||||
private String topic;
|
|
||||||
private ClientRunningData clientData;
|
|
||||||
private IZkDataListener dataListener;
|
|
||||||
private BooleanMutex mutex = new BooleanMutex(false);
|
|
||||||
private volatile boolean release = false;
|
|
||||||
private volatile ClientRunningData activeData;
|
|
||||||
private ScheduledExecutorService delayExector = Executors.newScheduledThreadPool(1);
|
|
||||||
private ClientRunningListener listener;
|
|
||||||
private int delayTime = 5;
|
|
||||||
|
|
||||||
private static Integer virtualPort;
|
|
||||||
|
|
||||||
public ClientRunningMonitor(){
|
|
||||||
if (virtualPort == null) {
|
|
||||||
Random rand = new Random();
|
|
||||||
virtualPort = rand.nextInt(9000) + 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
dataListener = new IZkDataListener() {
|
|
||||||
|
|
||||||
public void handleDataChange(String dataPath, Object data) throws Exception {
|
|
||||||
MDC.put("kafkaTopic", topic);
|
|
||||||
ClientRunningData runningData = JsonUtils.unmarshalFromByte((byte[]) data, ClientRunningData.class);
|
|
||||||
if (!isMine(runningData.getAddress())) {
|
|
||||||
mutex.set(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!runningData.isActive() && isMine(runningData.getAddress())) { // 说明出现了主动释放的操作,并且本机之前是active
|
|
||||||
release = true;
|
|
||||||
releaseRunning();// 彻底释放mainstem
|
|
||||||
}
|
|
||||||
|
|
||||||
activeData = (ClientRunningData) runningData;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void handleDataDeleted(String dataPath) throws Exception {
|
|
||||||
MDC.put("kafkaTopic", topic);
|
|
||||||
|
|
||||||
mutex.set(false);
|
|
||||||
// 触发一下退出,可能是人为干预的释放操作或者网络闪断引起的session expired timeout
|
|
||||||
processActiveExit();
|
|
||||||
if (!release && activeData != null && isMine(activeData.getAddress())) {
|
|
||||||
// 如果上一次active的状态就是本机,则即时触发一下active抢占
|
|
||||||
initRunning();
|
|
||||||
} else {
|
|
||||||
// 否则就是等待delayTime,避免因网络瞬端或者zk异常,导致出现频繁的切换操作
|
|
||||||
delayExector.schedule(new Runnable() {
|
|
||||||
|
|
||||||
public void run() {
|
|
||||||
initRunning();
|
|
||||||
}
|
|
||||||
}, delayTime, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void start() {
|
|
||||||
super.start();
|
|
||||||
|
|
||||||
String path = getTopicClientRunning(this.topic, clientData.getGroupId());
|
|
||||||
|
|
||||||
zkClient.subscribeDataChanges(path, dataListener);
|
|
||||||
initRunning();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void stop() {
|
|
||||||
super.stop();
|
|
||||||
String path = getTopicClientRunning(this.topic, clientData.getGroupId());
|
|
||||||
zkClient.unsubscribeDataChanges(path, dataListener);
|
|
||||||
releaseRunning(); // 尝试一下release
|
|
||||||
// Fix issue #697
|
|
||||||
if (delayExector != null) {
|
|
||||||
delayExector.shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 改动记录:
|
|
||||||
// 1,在方法上加synchronized关键字,保证同步顺序执行;
|
|
||||||
// 2,判断Zk上已经存在的activeData是否是本机,是的话把mutex重置为true,否则会导致死锁
|
|
||||||
// 3,增加异常处理,保证出现异常时,running节点能被删除,否则会导致死锁
|
|
||||||
public synchronized void initRunning() {
|
|
||||||
if (!isStart()) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
String path = getTopicClientRunning(this.topic, clientData.getGroupId());
|
|
||||||
// 序列化
|
|
||||||
byte[] bytes = JsonUtils.marshalToByte(clientData);
|
|
||||||
try {
|
|
||||||
mutex.set(false);
|
|
||||||
zkClient.create(path, bytes, CreateMode.EPHEMERAL);
|
|
||||||
processActiveEnter();// 触发一下事件
|
|
||||||
activeData = clientData;
|
|
||||||
mutex.set(true);
|
|
||||||
} catch (ZkNodeExistsException e) {
|
|
||||||
bytes = zkClient.readData(path, true);
|
|
||||||
if (bytes == null) {// 如果不存在节点,立即尝试一次
|
|
||||||
initRunning();
|
|
||||||
} else {
|
|
||||||
activeData = JsonUtils.unmarshalFromByte(bytes, ClientRunningData.class);
|
|
||||||
// 如果发现已经存在,判断一下是否自己,避免活锁
|
|
||||||
if (activeData.getAddress().contains(":") && isMine(activeData.getAddress())) {
|
|
||||||
mutex.set(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (ZkNoNodeException e) {
|
|
||||||
zkClient.createPersistent(getClientIdNodePath(this.topic, clientData.getGroupId()), true); // 尝试创建父节点
|
|
||||||
initRunning();
|
|
||||||
} catch (Throwable t) {
|
|
||||||
logger.error(MessageFormat.format("There is an error when execute initRunning method, with destination [{0}].",
|
|
||||||
topic),
|
|
||||||
t);
|
|
||||||
// 出现任何异常尝试release
|
|
||||||
releaseRunning();
|
|
||||||
throw new CanalClientException("something goes wrong in initRunning method. ", t);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 阻塞等待自己成为active,如果自己成为active,立马返回
|
|
||||||
*
|
|
||||||
* @throws InterruptedException
|
|
||||||
*/
|
|
||||||
public void waitForActive() throws InterruptedException {
|
|
||||||
initRunning();
|
|
||||||
mutex.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 检查当前的状态
|
|
||||||
*/
|
|
||||||
public boolean check() {
|
|
||||||
String path = getTopicClientRunning(this.topic, clientData.getGroupId());
|
|
||||||
// ZookeeperPathUtils.getDestinationClientRunning(this.destination,
|
|
||||||
// clientData.getClientId());
|
|
||||||
try {
|
|
||||||
byte[] bytes = zkClient.readData(path);
|
|
||||||
ClientRunningData eventData = JsonUtils.unmarshalFromByte(bytes, ClientRunningData.class);
|
|
||||||
activeData = eventData;// 更新下为最新值
|
|
||||||
// 检查下nid是否为自己
|
|
||||||
boolean result = isMine(activeData.getAddress());
|
|
||||||
if (!result) {
|
|
||||||
logger.warn("canal is running in [{}] , but not in [{}]",
|
|
||||||
activeData.getAddress(),
|
|
||||||
clientData.getAddress());
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
} catch (ZkNoNodeException e) {
|
|
||||||
logger.warn("canal is not run any in node");
|
|
||||||
return false;
|
|
||||||
} catch (ZkInterruptedException e) {
|
|
||||||
logger.warn("canal check is interrupt");
|
|
||||||
Thread.interrupted();// 清除interrupt标记
|
|
||||||
return check();
|
|
||||||
} catch (ZkException e) {
|
|
||||||
logger.warn("canal check is failed");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean releaseRunning() {
|
|
||||||
if (check()) {
|
|
||||||
String path = getTopicClientRunning(this.topic, clientData.getGroupId());
|
|
||||||
zkClient.delete(path);
|
|
||||||
mutex.set(false);
|
|
||||||
processActiveExit();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ====================== helper method ======================
|
|
||||||
|
|
||||||
private boolean isMine(String address) {
|
|
||||||
return address.equals(clientData.getAddress());
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processActiveEnter() {
|
|
||||||
if (listener != null) {
|
|
||||||
// 触发回调
|
|
||||||
listener.processActiveEnter();
|
|
||||||
this.clientData.setAddress(/* address */AddressUtils.getHostIp() + ":" + virtualPort);
|
|
||||||
|
|
||||||
String path = getTopicClientRunning(this.topic, clientData.getGroupId());
|
|
||||||
// 序列化
|
|
||||||
byte[] bytes = JsonUtils.marshalToByte(clientData);
|
|
||||||
zkClient.writeData(path, bytes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processActiveExit() {
|
|
||||||
if (listener != null) {
|
|
||||||
listener.processActiveExit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setListener(ClientRunningListener listener) {
|
|
||||||
this.listener = listener;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===================== setter / getter =======================
|
|
||||||
|
|
||||||
public void setTopic(String topic) {
|
|
||||||
this.topic = topic;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setClientData(ClientRunningData clientData) {
|
|
||||||
this.clientData = clientData;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDelayTime(int delayTime) {
|
|
||||||
this.delayTime = delayTime;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setZkClient(ZkClientx zkClient) {
|
|
||||||
this.zkClient = zkClient;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package com.alibaba.otter.canal.client.rocketmq;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CountDownLatch;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
public class ConsumerBatchMessage<T> {
|
||||||
|
|
||||||
|
private final List<T> data;
|
||||||
|
private CountDownLatch latch;
|
||||||
|
private boolean hasFailure = false;
|
||||||
|
|
||||||
|
public ConsumerBatchMessage(List<T> data){
|
||||||
|
this.data = data;
|
||||||
|
latch = new CountDownLatch(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean waitFinish(long timeout) throws InterruptedException {
|
||||||
|
return latch.await(timeout, TimeUnit.MILLISECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isSuccess() {
|
||||||
|
return !hasFailure;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<T> getData() {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Countdown if the sub message is successful.
|
||||||
|
*/
|
||||||
|
public void ack() {
|
||||||
|
latch.countDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Countdown and fail-fast if the sub message is failed.
|
||||||
|
*/
|
||||||
|
public void fail() {
|
||||||
|
hasFailure = true;
|
||||||
|
// fail fast
|
||||||
|
long count = latch.getCount();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
latch.countDown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
package com.alibaba.otter.canal.client.rocketmq;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.BlockingQueue;
|
||||||
|
import java.util.concurrent.LinkedBlockingQueue;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.commons.lang.StringUtils;
|
||||||
|
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
|
||||||
|
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
|
||||||
|
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
|
||||||
|
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
|
||||||
|
import org.apache.rocketmq.client.exception.MQClientException;
|
||||||
|
import org.apache.rocketmq.common.message.MessageExt;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSON;
|
||||||
|
import com.alibaba.otter.canal.client.CanalMQConnector;
|
||||||
|
import com.alibaba.otter.canal.client.CanalMessageDeserializer;
|
||||||
|
import com.alibaba.otter.canal.client.impl.SimpleCanalConnector;
|
||||||
|
import com.alibaba.otter.canal.protocol.FlatMessage;
|
||||||
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
import com.alibaba.otter.canal.protocol.exception.CanalClientException;
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RocketMQ的连接
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* 注意点:
|
||||||
|
* 1. 相比于canal {@linkplain SimpleCanalConnector}, 这里get和ack操作不能有并发, 必须是一个线程执行get后,内存里执行完毕ack后再取下一个get
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @since 1.1.1
|
||||||
|
*/
|
||||||
|
public class RocketMQCanalConnector implements CanalMQConnector {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(RocketMQCanalConnector.class);
|
||||||
|
|
||||||
|
private String nameServer;
|
||||||
|
private String topic;
|
||||||
|
private String groupName;
|
||||||
|
private volatile boolean connected = false;
|
||||||
|
private DefaultMQPushConsumer rocketMQConsumer;
|
||||||
|
private BlockingQueue<ConsumerBatchMessage> messageBlockingQueue;
|
||||||
|
private long batchProcessTimeout = 60 * 1000;
|
||||||
|
private boolean flatMessage;
|
||||||
|
private volatile ConsumerBatchMessage lastGetBatchMessage = null;
|
||||||
|
|
||||||
|
public RocketMQCanalConnector(String nameServer, String topic, String groupName, boolean flatMessage){
|
||||||
|
this.nameServer = nameServer;
|
||||||
|
this.topic = topic;
|
||||||
|
this.groupName = groupName;
|
||||||
|
this.flatMessage = flatMessage;
|
||||||
|
this.messageBlockingQueue = new LinkedBlockingQueue<>(1024);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void connect() throws CanalClientException {
|
||||||
|
rocketMQConsumer = new DefaultMQPushConsumer(groupName);
|
||||||
|
if (!StringUtils.isBlank(nameServer)) {
|
||||||
|
rocketMQConsumer.setNamesrvAddr(nameServer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void disconnect() throws CanalClientException {
|
||||||
|
rocketMQConsumer.shutdown();
|
||||||
|
connected = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean checkValid() throws CanalClientException {
|
||||||
|
return connected;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void subscribe(String filter) throws CanalClientException {
|
||||||
|
if (connected) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (rocketMQConsumer == null) {
|
||||||
|
this.connect();
|
||||||
|
}
|
||||||
|
rocketMQConsumer.subscribe(this.topic, "*");
|
||||||
|
rocketMQConsumer.registerMessageListener(new MessageListenerOrderly() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ConsumeOrderlyStatus consumeMessage(List<MessageExt> messageExts, ConsumeOrderlyContext context) {
|
||||||
|
context.setAutoCommit(true);
|
||||||
|
boolean isSuccess = process(messageExts);
|
||||||
|
if (isSuccess) {
|
||||||
|
return ConsumeOrderlyStatus.SUCCESS;
|
||||||
|
} else {
|
||||||
|
return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
rocketMQConsumer.start();
|
||||||
|
} catch (MQClientException ex) {
|
||||||
|
connected = false;
|
||||||
|
logger.error("Start RocketMQ consumer error", ex);
|
||||||
|
}
|
||||||
|
connected = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean process(List<MessageExt> messageExts) {
|
||||||
|
logger.info("Get Message:{}", messageExts);
|
||||||
|
List messageList = Lists.newArrayList();
|
||||||
|
for (MessageExt messageExt : messageExts) {
|
||||||
|
byte[] data = messageExt.getBody();
|
||||||
|
if (data != null) {
|
||||||
|
try {
|
||||||
|
if (!flatMessage) {
|
||||||
|
Message message = CanalMessageDeserializer.deserializer(data);
|
||||||
|
messageList.add(message);
|
||||||
|
} else {
|
||||||
|
FlatMessage flatMessage = JSON.parseObject(data, FlatMessage.class);
|
||||||
|
messageList.add(flatMessage);
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
logger.error("Add message error", ex);
|
||||||
|
throw new CanalClientException(ex);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.warn("Received message data is null");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ConsumerBatchMessage batchMessage;
|
||||||
|
if (!flatMessage) {
|
||||||
|
batchMessage = new ConsumerBatchMessage<Message>(messageList);
|
||||||
|
} else {
|
||||||
|
batchMessage = new ConsumerBatchMessage<FlatMessage>(messageList);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
messageBlockingQueue.put(batchMessage);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
logger.error("Put message to queue error", e);
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
boolean isCompleted;
|
||||||
|
try {
|
||||||
|
isCompleted = batchMessage.waitFinish(batchProcessTimeout);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
logger.error("Interrupted when waiting messages to be finished.", e);
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
boolean isSuccess = batchMessage.isSuccess();
|
||||||
|
return isCompleted && isSuccess;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void subscribe() throws CanalClientException {
|
||||||
|
this.subscribe(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unsubscribe() throws CanalClientException {
|
||||||
|
this.rocketMQConsumer.unsubscribe(this.topic);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Message> getList(Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
List<Message> messages = getListWithoutAck(timeout, unit);
|
||||||
|
if (messages != null && !messages.isEmpty()) {
|
||||||
|
ack();
|
||||||
|
}
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Message> getListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
try {
|
||||||
|
if (this.lastGetBatchMessage != null) {
|
||||||
|
throw new CanalClientException("mq get/ack not support concurrent & async ack");
|
||||||
|
}
|
||||||
|
|
||||||
|
ConsumerBatchMessage batchMessage = messageBlockingQueue.poll(timeout, unit);
|
||||||
|
if (batchMessage != null) {
|
||||||
|
this.lastGetBatchMessage = batchMessage;
|
||||||
|
return batchMessage.getData();
|
||||||
|
}
|
||||||
|
} catch (InterruptedException ex) {
|
||||||
|
logger.warn("Get message timeout", ex);
|
||||||
|
throw new CanalClientException("Failed to fetch the data after: " + timeout);
|
||||||
|
}
|
||||||
|
return Lists.newArrayList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FlatMessage> getFlatList(Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
List<FlatMessage> messages = getFlatListWithoutAck(timeout, unit);
|
||||||
|
if (messages != null && !messages.isEmpty()) {
|
||||||
|
ack();
|
||||||
|
}
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<FlatMessage> getFlatListWithoutAck(Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
try {
|
||||||
|
if (this.lastGetBatchMessage != null) {
|
||||||
|
throw new CanalClientException("mq get/ack not support concurrent & async ack");
|
||||||
|
}
|
||||||
|
|
||||||
|
ConsumerBatchMessage batchMessage = messageBlockingQueue.poll(timeout, unit);
|
||||||
|
if (batchMessage != null) {
|
||||||
|
this.lastGetBatchMessage = batchMessage;
|
||||||
|
return batchMessage.getData();
|
||||||
|
}
|
||||||
|
} catch (InterruptedException ex) {
|
||||||
|
logger.warn("Get message timeout", ex);
|
||||||
|
throw new CanalClientException("Failed to fetch the data after: " + timeout);
|
||||||
|
}
|
||||||
|
return Lists.newArrayList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void ack() throws CanalClientException {
|
||||||
|
try {
|
||||||
|
this.lastGetBatchMessage.ack();
|
||||||
|
} catch (Throwable e) {
|
||||||
|
this.lastGetBatchMessage.fail();
|
||||||
|
} finally {
|
||||||
|
this.lastGetBatchMessage = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void rollback() throws CanalClientException {
|
||||||
|
try {
|
||||||
|
this.lastGetBatchMessage.fail();
|
||||||
|
} finally {
|
||||||
|
this.lastGetBatchMessage = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Message get(int batchSize) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Message get(int batchSize, Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Message getWithoutAck(int batchSize) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Message getWithoutAck(int batchSize, Long timeout, TimeUnit unit) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void ack(long batchId) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void rollback(long batchId) throws CanalClientException {
|
||||||
|
throw new CanalClientException("mq not support this method");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.alibaba.otter.canal.client.rocketmq;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RocketMQ connector provider.
|
||||||
|
*/
|
||||||
|
public class RocketMQCanalConnectors {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create RocketMQ connector
|
||||||
|
*
|
||||||
|
* @param nameServers name servers for RocketMQ
|
||||||
|
* @param topic
|
||||||
|
* @param groupId
|
||||||
|
* @return {@link RocketMQCanalConnector}
|
||||||
|
*/
|
||||||
|
public static RocketMQCanalConnector newRocketMQConnector(String nameServers, String topic, String groupId) {
|
||||||
|
return new RocketMQCanalConnector(nameServers, topic, groupId, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static RocketMQCanalConnector newRocketMQConnector(String nameServers, String topic, String groupId,
|
||||||
|
boolean flatMessage) {
|
||||||
|
return new RocketMQCanalConnector(nameServers, topic, groupId, flatMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.running.kafka;
|
package com.alibaba.otter.canal.client.running.kafka;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
import org.apache.kafka.common.errors.WakeupException;
|
import org.apache.kafka.common.errors.WakeupException;
|
||||||
@@ -35,7 +36,7 @@ public class CanalKafkaClientExample {
|
|||||||
};
|
};
|
||||||
|
|
||||||
public CanalKafkaClientExample(String zkServers, String servers, String topic, Integer partition, String groupId){
|
public CanalKafkaClientExample(String zkServers, String servers, String topic, Integer partition, String groupId){
|
||||||
connector = KafkaCanalConnectors.newKafkaConnector(zkServers, servers, topic, partition, groupId);
|
connector = KafkaCanalConnectors.newKafkaConnector(servers, topic, partition, groupId, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
@@ -87,7 +88,6 @@ public class CanalKafkaClientExample {
|
|||||||
if (!running) {
|
if (!running) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
connector.stopRunning();
|
|
||||||
running = false;
|
running = false;
|
||||||
if (thread != null) {
|
if (thread != null) {
|
||||||
try {
|
try {
|
||||||
@@ -107,10 +107,11 @@ public class CanalKafkaClientExample {
|
|||||||
connector.subscribe();
|
connector.subscribe();
|
||||||
while (running) {
|
while (running) {
|
||||||
try {
|
try {
|
||||||
Message message = connector.getWithoutAck(1L, TimeUnit.SECONDS); // 获取message
|
List<Message> messages = connector.getListWithoutAck(100L, TimeUnit.MILLISECONDS); // 获取message
|
||||||
if (message == null) {
|
if (messages == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
for (Message message : messages) {
|
||||||
long batchId = message.getId();
|
long batchId = message.getId();
|
||||||
int size = message.getEntries().size();
|
int size = message.getEntries().size();
|
||||||
if (batchId == -1 || size == 0) {
|
if (batchId == -1 || size == 0) {
|
||||||
@@ -123,6 +124,7 @@ public class CanalKafkaClientExample {
|
|||||||
// printEntry(message.getEntries());
|
// printEntry(message.getEntries());
|
||||||
logger.info(message.toString());
|
logger.info(message.toString());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
connector.ack(); // 提交确认
|
connector.ack(); // 提交确认
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -139,6 +141,6 @@ public class CanalKafkaClientExample {
|
|||||||
} catch (WakeupException e) {
|
} catch (WakeupException e) {
|
||||||
// No-op. Continue process
|
// No-op. Continue process
|
||||||
}
|
}
|
||||||
connector.disconnnect();
|
connector.disconnect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.alibaba.otter.canal.client.running.kafka;
|
package com.alibaba.otter.canal.client.running.kafka;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
@@ -39,9 +40,9 @@ public class KafkaClientRunningTest extends AbstractKafkaTest {
|
|||||||
connector.subscribe();
|
connector.subscribe();
|
||||||
while (running) {
|
while (running) {
|
||||||
try {
|
try {
|
||||||
Message message = connector.getWithoutAck(3L, TimeUnit.SECONDS);
|
List<Message> messages = connector.getList(3L, TimeUnit.SECONDS);
|
||||||
if (message != null) {
|
if (messages != null) {
|
||||||
System.out.println(message);
|
System.out.println(messages);
|
||||||
}
|
}
|
||||||
connector.ack();
|
connector.ack();
|
||||||
} catch (WakeupException e) {
|
} catch (WakeupException e) {
|
||||||
@@ -49,7 +50,7 @@ public class KafkaClientRunningTest extends AbstractKafkaTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
connector.unsubscribe();
|
connector.unsubscribe();
|
||||||
connector.disconnnect();
|
connector.disconnect();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.alibaba.otter.canal.client.running.rocketmq;
|
||||||
|
|
||||||
|
public class AbstractRocektMQTest {
|
||||||
|
|
||||||
|
public static String topic = "example";
|
||||||
|
public static String groupId = "group";
|
||||||
|
public static String nameServers = "localhost:9876";
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package com.alibaba.otter.canal.client.running.rocketmq;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import org.apache.kafka.common.errors.WakeupException;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
|
import com.alibaba.otter.canal.client.rocketmq.RocketMQCanalConnector;
|
||||||
|
import com.alibaba.otter.canal.client.rocketmq.RocketMQCanalConnectors;
|
||||||
|
import com.alibaba.otter.canal.client.running.kafka.AbstractKafkaTest;
|
||||||
|
import com.alibaba.otter.canal.protocol.Message;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Kafka client example
|
||||||
|
*
|
||||||
|
* @author machengyuan @ 2018-6-12
|
||||||
|
* @version 1.0.0
|
||||||
|
*/
|
||||||
|
public class CanalRocketMQClientExample extends AbstractRocektMQTest {
|
||||||
|
|
||||||
|
protected final static Logger logger = LoggerFactory.getLogger(CanalRocketMQClientExample.class);
|
||||||
|
|
||||||
|
private RocketMQCanalConnector connector;
|
||||||
|
|
||||||
|
private static volatile boolean running = false;
|
||||||
|
|
||||||
|
private Thread thread = null;
|
||||||
|
|
||||||
|
private Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
|
||||||
|
|
||||||
|
public void uncaughtException(Thread t, Throwable e) {
|
||||||
|
logger.error("parse events has an error", e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
public CanalRocketMQClientExample(String nameServers, String topic, String groupId){
|
||||||
|
connector = RocketMQCanalConnectors.newRocketMQConnector(nameServers, topic, groupId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
try {
|
||||||
|
final CanalRocketMQClientExample rocketMQClientExample = new CanalRocketMQClientExample(nameServers,
|
||||||
|
topic,
|
||||||
|
groupId);
|
||||||
|
logger.info("## Start the rocketmq consumer: {}-{}", AbstractKafkaTest.topic, AbstractKafkaTest.groupId);
|
||||||
|
rocketMQClientExample.start();
|
||||||
|
logger.info("## The canal rocketmq consumer is running now ......");
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread() {
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
try {
|
||||||
|
logger.info("## Stop the rocketmq consumer");
|
||||||
|
rocketMQClientExample.stop();
|
||||||
|
} catch (Throwable e) {
|
||||||
|
logger.warn("## Something goes wrong when stopping rocketmq consumer:", e);
|
||||||
|
} finally {
|
||||||
|
logger.info("## Rocketmq consumer is down.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
});
|
||||||
|
while (running)
|
||||||
|
;
|
||||||
|
} catch (Throwable e) {
|
||||||
|
logger.error("## Something going wrong when starting up the rocketmq consumer:", e);
|
||||||
|
System.exit(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void start() {
|
||||||
|
Assert.notNull(connector, "connector is null");
|
||||||
|
thread = new Thread(new Runnable() {
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
process();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
thread.setUncaughtExceptionHandler(handler);
|
||||||
|
thread.start();
|
||||||
|
running = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void stop() {
|
||||||
|
if (!running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
running = false;
|
||||||
|
if (thread != null) {
|
||||||
|
try {
|
||||||
|
thread.join();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void process() {
|
||||||
|
while (!running)
|
||||||
|
;
|
||||||
|
while (running) {
|
||||||
|
try {
|
||||||
|
connector.connect();
|
||||||
|
connector.subscribe();
|
||||||
|
while (running) {
|
||||||
|
List<Message> messages = connector.getListWithoutAck(100L, TimeUnit.MILLISECONDS); // 获取message
|
||||||
|
for (Message message : messages) {
|
||||||
|
long batchId = message.getId();
|
||||||
|
int size = message.getEntries().size();
|
||||||
|
if (batchId == -1 || size == 0) {
|
||||||
|
// try {
|
||||||
|
// Thread.sleep(1000);
|
||||||
|
// } catch (InterruptedException e) {
|
||||||
|
// }
|
||||||
|
} else {
|
||||||
|
// printSummary(message, batchId, size);
|
||||||
|
// printEntry(message.getEntries());
|
||||||
|
logger.info(message.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connector.ack(); // 提交确认
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error(e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
connector.unsubscribe();
|
||||||
|
} catch (WakeupException e) {
|
||||||
|
// No-op. Continue process
|
||||||
|
}
|
||||||
|
// connector.stopRunning();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<artifactId>canal</artifactId>
|
<artifactId>canal</artifactId>
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
<version>1.1.1</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<artifactId>canal.common</artifactId>
|
<artifactId>canal.common</artifactId>
|
||||||
@@ -83,6 +83,10 @@
|
|||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-orm</artifactId>
|
<artifactId>spring-orm</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.code.findbugs</groupId>
|
||||||
|
<artifactId>jsr305</artifactId>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-test</artifactId>
|
<artifactId>spring-test</artifactId>
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import java.util.concurrent.TimeoutException;
|
|||||||
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
|
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 实现一个互斥实现,基于Cocurrent中的{@linkplain AbstractQueuedSynchronizer}实现了自己的sync <br/>
|
* 实现一个互斥实现,基于Cocurrent中的AbstractQueuedSynchronizer实现了自己的sync <br/>
|
||||||
* 应用场景:系统初始化/授权控制,没权限时阻塞等待。有权限时所有线程都可以快速通过
|
* 应用场景:系统初始化/授权控制,没权限时阻塞等待。有权限时所有线程都可以快速通过
|
||||||
*
|
*
|
||||||
* <pre>
|
* <pre>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<artifactId>canal</artifactId>
|
<artifactId>canal</artifactId>
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
<version>1.1.1</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import java.util.Map;
|
|||||||
|
|
||||||
import com.alibaba.otter.canal.parse.driver.mysql.packets.GTIDSet;
|
import com.alibaba.otter.canal.parse.driver.mysql.packets.GTIDSet;
|
||||||
import com.taobao.tddl.dbsync.binlog.event.FormatDescriptionLogEvent;
|
import com.taobao.tddl.dbsync.binlog.event.FormatDescriptionLogEvent;
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.GtidLogEvent;
|
||||||
import com.taobao.tddl.dbsync.binlog.event.TableMapLogEvent;
|
import com.taobao.tddl.dbsync.binlog.event.TableMapLogEvent;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,6 +24,8 @@ public final class LogContext {
|
|||||||
|
|
||||||
private GTIDSet gtidSet;
|
private GTIDSet gtidSet;
|
||||||
|
|
||||||
|
private GtidLogEvent gtidLogEvent; // save current gtid log event
|
||||||
|
|
||||||
public LogContext(){
|
public LogContext(){
|
||||||
this.formatDescription = FormatDescriptionLogEvent.FORMAT_DESCRIPTION_EVENT_5_x;
|
this.formatDescription = FormatDescriptionLogEvent.FORMAT_DESCRIPTION_EVENT_5_x;
|
||||||
}
|
}
|
||||||
@@ -71,4 +74,12 @@ public final class LogContext {
|
|||||||
public void setGtidSet(GTIDSet gtidSet) {
|
public void setGtidSet(GTIDSet gtidSet) {
|
||||||
this.gtidSet = gtidSet;
|
this.gtidSet = gtidSet;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public GtidLogEvent getGtidLogEvent() {
|
||||||
|
return gtidLogEvent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGtidLogEvent(GtidLogEvent gtidLogEvent) {
|
||||||
|
this.gtidLogEvent = gtidLogEvent;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -161,19 +161,20 @@ public final class LogDecoder {
|
|||||||
buffer.limit(header.getEventLen() - LogEvent.BINLOG_CHECKSUM_LEN);
|
buffer.limit(header.getEventLen() - LogEvent.BINLOG_CHECKSUM_LEN);
|
||||||
}
|
}
|
||||||
GTIDSet gtidSet = context.getGtidSet();
|
GTIDSet gtidSet = context.getGtidSet();
|
||||||
|
GtidLogEvent gtidLogEvent = context.getGtidLogEvent();
|
||||||
switch (header.getType()) {
|
switch (header.getType()) {
|
||||||
case LogEvent.QUERY_EVENT: {
|
case LogEvent.QUERY_EVENT: {
|
||||||
QueryLogEvent event = new QueryLogEvent(header, buffer, descriptionEvent);
|
QueryLogEvent event = new QueryLogEvent(header, buffer, descriptionEvent);
|
||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.XID_EVENT: {
|
case LogEvent.XID_EVENT: {
|
||||||
XidLogEvent event = new XidLogEvent(header, buffer, descriptionEvent);
|
XidLogEvent event = new XidLogEvent(header, buffer, descriptionEvent);
|
||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.TABLE_MAP_EVENT: {
|
case LogEvent.TABLE_MAP_EVENT: {
|
||||||
@@ -188,6 +189,7 @@ public final class LogDecoder {
|
|||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
event.fillTable(context);
|
event.fillTable(context);
|
||||||
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.UPDATE_ROWS_EVENT_V1: {
|
case LogEvent.UPDATE_ROWS_EVENT_V1: {
|
||||||
@@ -195,6 +197,7 @@ public final class LogDecoder {
|
|||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
event.fillTable(context);
|
event.fillTable(context);
|
||||||
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.DELETE_ROWS_EVENT_V1: {
|
case LogEvent.DELETE_ROWS_EVENT_V1: {
|
||||||
@@ -202,6 +205,7 @@ public final class LogDecoder {
|
|||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
event.fillTable(context);
|
event.fillTable(context);
|
||||||
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.ROTATE_EVENT: {
|
case LogEvent.ROTATE_EVENT: {
|
||||||
@@ -271,14 +275,14 @@ public final class LogDecoder {
|
|||||||
RandLogEvent event = new RandLogEvent(header, buffer, descriptionEvent);
|
RandLogEvent event = new RandLogEvent(header, buffer, descriptionEvent);
|
||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.USER_VAR_EVENT: {
|
case LogEvent.USER_VAR_EVENT: {
|
||||||
UserVarLogEvent event = new UserVarLogEvent(header, buffer, descriptionEvent);
|
UserVarLogEvent event = new UserVarLogEvent(header, buffer, descriptionEvent);
|
||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.FORMAT_DESCRIPTION_EVENT: {
|
case LogEvent.FORMAT_DESCRIPTION_EVENT: {
|
||||||
@@ -329,7 +333,6 @@ public final class LogDecoder {
|
|||||||
HeartbeatLogEvent event = new HeartbeatLogEvent(header, buffer, descriptionEvent);
|
HeartbeatLogEvent event = new HeartbeatLogEvent(header, buffer, descriptionEvent);
|
||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
header.putGtidStr(context.getGtidSet());
|
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.IGNORABLE_LOG_EVENT: {
|
case LogEvent.IGNORABLE_LOG_EVENT: {
|
||||||
@@ -342,7 +345,7 @@ public final class LogDecoder {
|
|||||||
RowsQueryLogEvent event = new RowsQueryLogEvent(header, buffer, descriptionEvent);
|
RowsQueryLogEvent event = new RowsQueryLogEvent(header, buffer, descriptionEvent);
|
||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.WRITE_ROWS_EVENT: {
|
case LogEvent.WRITE_ROWS_EVENT: {
|
||||||
@@ -350,7 +353,7 @@ public final class LogDecoder {
|
|||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
event.fillTable(context);
|
event.fillTable(context);
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.UPDATE_ROWS_EVENT: {
|
case LogEvent.UPDATE_ROWS_EVENT: {
|
||||||
@@ -358,7 +361,7 @@ public final class LogDecoder {
|
|||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
event.fillTable(context);
|
event.fillTable(context);
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.DELETE_ROWS_EVENT: {
|
case LogEvent.DELETE_ROWS_EVENT: {
|
||||||
@@ -366,7 +369,7 @@ public final class LogDecoder {
|
|||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
event.fillTable(context);
|
event.fillTable(context);
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.GTID_LOG_EVENT:
|
case LogEvent.GTID_LOG_EVENT:
|
||||||
@@ -377,8 +380,10 @@ public final class LogDecoder {
|
|||||||
if (gtidSet != null) {
|
if (gtidSet != null) {
|
||||||
gtidSet.update(event.getGtidStr());
|
gtidSet.update(event.getGtidStr());
|
||||||
// update latest gtid
|
// update latest gtid
|
||||||
header.putGtidStr(gtidSet);
|
header.putGtid(gtidSet, event);
|
||||||
}
|
}
|
||||||
|
// update current gtid event to context
|
||||||
|
context.setGtidLogEvent(event);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.PREVIOUS_GTIDS_LOG_EVENT: {
|
case LogEvent.PREVIOUS_GTIDS_LOG_EVENT: {
|
||||||
@@ -409,7 +414,7 @@ public final class LogDecoder {
|
|||||||
AnnotateRowsEvent event = new AnnotateRowsEvent(header, buffer, descriptionEvent);
|
AnnotateRowsEvent event = new AnnotateRowsEvent(header, buffer, descriptionEvent);
|
||||||
/* updating position in context */
|
/* updating position in context */
|
||||||
logPosition.position = header.getLogPos();
|
logPosition.position = header.getLogPos();
|
||||||
header.putGtidStr(context.getGtidSet());
|
header.putGtid(context.getGtidSet(), gtidLogEvent);
|
||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
case LogEvent.BINLOG_CHECKPOINT_EVENT: {
|
case LogEvent.BINLOG_CHECKPOINT_EVENT: {
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import com.alibaba.otter.canal.parse.driver.mysql.packets.GTIDSet;
|
|||||||
import com.taobao.tddl.dbsync.binlog.LogBuffer;
|
import com.taobao.tddl.dbsync.binlog.LogBuffer;
|
||||||
import com.taobao.tddl.dbsync.binlog.LogEvent;
|
import com.taobao.tddl.dbsync.binlog.LogEvent;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The Common-Header, documented in the table @ref Table_common_header "below",
|
* The Common-Header, documented in the table @ref Table_common_header "below",
|
||||||
* always has the same form and length within one version of MySQL. Each event
|
* always has the same form and length within one version of MySQL. Each event
|
||||||
@@ -121,7 +124,12 @@ public final class LogHeader {
|
|||||||
*/
|
*/
|
||||||
protected String logFileName;
|
protected String logFileName;
|
||||||
|
|
||||||
protected String gtidStr;
|
protected Map<String, String> gtidMap = new HashMap<>();
|
||||||
|
|
||||||
|
private static final String CURRENT_GTID_STRING = "curt_gtid";
|
||||||
|
private static final String CURRENT_GTID_SN = "curt_gtid_sn";
|
||||||
|
private static final String CURRENT_GTID_LAST_COMMIT = "curt_gtid_lct";
|
||||||
|
private static final String GTID_SET_STRING = "gtid_str";
|
||||||
|
|
||||||
/* for Start_event_v3 */
|
/* for Start_event_v3 */
|
||||||
public LogHeader(final int type){
|
public LogHeader(final int type){
|
||||||
@@ -292,13 +300,30 @@ public final class LogHeader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getGtidStr() {
|
public String getGtidSetStr() {
|
||||||
return gtidStr;
|
return gtidMap.get(GTID_SET_STRING);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void putGtidStr(GTIDSet gtidSet) {
|
public String getCurrentGtid() {
|
||||||
|
return gtidMap.get(CURRENT_GTID_STRING);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCurrentGtidSn() {
|
||||||
|
return gtidMap.get(CURRENT_GTID_SN);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCurrentGtidLastCommit() {
|
||||||
|
return gtidMap.get(CURRENT_GTID_LAST_COMMIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void putGtid(GTIDSet gtidSet, GtidLogEvent event) {
|
||||||
if (gtidSet != null) {
|
if (gtidSet != null) {
|
||||||
this.gtidStr = gtidSet.toString();
|
gtidMap.put(GTID_SET_STRING, gtidSet.toString());
|
||||||
|
if (event != null) {
|
||||||
|
gtidMap.put(CURRENT_GTID_STRING, event.getGtidStr());
|
||||||
|
gtidMap.put(CURRENT_GTID_SN, String.valueOf(event.getSequenceNumber()));
|
||||||
|
gtidMap.put(CURRENT_GTID_LAST_COMMIT, String.valueOf(event.getLastCommitted()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -367,7 +367,7 @@ public final class RowsLogBuffer {
|
|||||||
// 转化为unsign long
|
// 转化为unsign long
|
||||||
switch (len) {
|
switch (len) {
|
||||||
case 1:
|
case 1:
|
||||||
value = buffer.getInt8();
|
value = buffer.getUint8();
|
||||||
break;
|
break;
|
||||||
case 2:
|
case 2:
|
||||||
value = buffer.getBeUint16();
|
value = buffer.getBeUint16();
|
||||||
@@ -859,7 +859,7 @@ public final class RowsLogBuffer {
|
|||||||
// 转化为unsign long
|
// 转化为unsign long
|
||||||
switch (len) {
|
switch (len) {
|
||||||
case 1:
|
case 1:
|
||||||
value = buffer.getInt8();
|
value = buffer.getUint8();
|
||||||
break;
|
break;
|
||||||
case 2:
|
case 2:
|
||||||
value = buffer.getUint16();
|
value = buffer.getUint16();
|
||||||
@@ -1082,10 +1082,10 @@ public final class RowsLogBuffer {
|
|||||||
buffer.fillBytes(binary, 0, len);
|
buffer.fillBytes(binary, 0, len);
|
||||||
|
|
||||||
/* Warning unsupport cloumn type */
|
/* Warning unsupport cloumn type */
|
||||||
logger.warn(String.format("!! Unsupport column type MYSQL_TYPE_GEOMETRY: meta=%d (%04X), len = %d",
|
// logger.warn(String.format("!! Unsupport column type MYSQL_TYPE_GEOMETRY: meta=%d (%04X), len = %d",
|
||||||
meta,
|
// meta,
|
||||||
meta,
|
// meta,
|
||||||
len));
|
// len));
|
||||||
javaType = Types.BINARY;
|
javaType = Types.BINARY;
|
||||||
value = binary;
|
value = binary;
|
||||||
length = len;
|
length = len;
|
||||||
|
|||||||
@@ -8,6 +8,15 @@ import java.sql.Statement;
|
|||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.DeleteRowsLogEvent;
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.QueryLogEvent;
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.RotateLogEvent;
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.RowsQueryLogEvent;
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.UpdateRowsLogEvent;
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.WriteRowsLogEvent;
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.XidLogEvent;
|
||||||
|
import com.taobao.tddl.dbsync.binlog.event.mariadb.AnnotateRowsEvent;
|
||||||
|
|
||||||
public class DirectLogFetcherTest extends BaseLogFetcherTest {
|
public class DirectLogFetcherTest extends BaseLogFetcherTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -15,54 +24,49 @@ public class DirectLogFetcherTest extends BaseLogFetcherTest {
|
|||||||
DirectLogFetcher fecther = new DirectLogFetcher();
|
DirectLogFetcher fecther = new DirectLogFetcher();
|
||||||
try {
|
try {
|
||||||
Class.forName("com.mysql.jdbc.Driver");
|
Class.forName("com.mysql.jdbc.Driver");
|
||||||
Connection connection = DriverManager.getConnection("jdbc:mysql://100.81.154.142:3306", "root", "hello");
|
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306", "root", "hello");
|
||||||
Statement statement = connection.createStatement();
|
Statement statement = connection.createStatement();
|
||||||
statement.execute("SET @master_binlog_checksum='@@global.binlog_checksum'");
|
statement.execute("SET @master_binlog_checksum='@@global.binlog_checksum'");
|
||||||
statement.execute("SET @mariadb_slave_capability='" + LogEvent.MARIA_SLAVE_CAPABILITY_MINE + "'");
|
statement.execute("SET @mariadb_slave_capability='" + LogEvent.MARIA_SLAVE_CAPABILITY_MINE + "'");
|
||||||
|
|
||||||
fecther.open(connection, "mysql-bin.000006", 120L, 2);
|
fecther.open(connection, "mysql-bin.000007", 89797036L, 2);
|
||||||
|
|
||||||
LogDecoder decoder = new LogDecoder(LogEvent.UNKNOWN_EVENT, LogEvent.UNKNOWN_EVENT);
|
LogDecoder decoder = new LogDecoder(LogEvent.UNKNOWN_EVENT, LogEvent.ENUM_END_EVENT);
|
||||||
LogContext context = new LogContext();
|
LogContext context = new LogContext();
|
||||||
while (fecther.fetch()) {
|
while (fecther.fetch()) {
|
||||||
decoder.decode(fecther, context);
|
LogEvent event = decoder.decode(fecther, context);
|
||||||
continue;
|
int eventType = event.getHeader().getType();
|
||||||
// if (event == null) {
|
switch (eventType) {
|
||||||
// continue;
|
case LogEvent.ROTATE_EVENT:
|
||||||
// }
|
binlogFileName = ((RotateLogEvent) event).getFilename();
|
||||||
//
|
break;
|
||||||
// int eventType = event.getHeader().getType();
|
case LogEvent.WRITE_ROWS_EVENT_V1:
|
||||||
// switch (eventType) {
|
case LogEvent.WRITE_ROWS_EVENT:
|
||||||
// case LogEvent.ROTATE_EVENT:
|
parseRowsEvent((WriteRowsLogEvent) event);
|
||||||
// binlogFileName = ((RotateLogEvent) event).getFilename();
|
break;
|
||||||
// break;
|
case LogEvent.UPDATE_ROWS_EVENT_V1:
|
||||||
// case LogEvent.WRITE_ROWS_EVENT_V1:
|
case LogEvent.UPDATE_ROWS_EVENT:
|
||||||
// case LogEvent.WRITE_ROWS_EVENT:
|
parseRowsEvent((UpdateRowsLogEvent) event);
|
||||||
// parseRowsEvent((WriteRowsLogEvent) event);
|
break;
|
||||||
// break;
|
case LogEvent.DELETE_ROWS_EVENT_V1:
|
||||||
// case LogEvent.UPDATE_ROWS_EVENT_V1:
|
case LogEvent.DELETE_ROWS_EVENT:
|
||||||
// case LogEvent.UPDATE_ROWS_EVENT:
|
parseRowsEvent((DeleteRowsLogEvent) event);
|
||||||
// parseRowsEvent((UpdateRowsLogEvent) event);
|
break;
|
||||||
// break;
|
case LogEvent.QUERY_EVENT:
|
||||||
// case LogEvent.DELETE_ROWS_EVENT_V1:
|
parseQueryEvent((QueryLogEvent) event);
|
||||||
// case LogEvent.DELETE_ROWS_EVENT:
|
break;
|
||||||
// parseRowsEvent((DeleteRowsLogEvent) event);
|
case LogEvent.ROWS_QUERY_LOG_EVENT:
|
||||||
// break;
|
parseRowsQueryEvent((RowsQueryLogEvent) event);
|
||||||
// case LogEvent.QUERY_EVENT:
|
break;
|
||||||
// parseQueryEvent((QueryLogEvent) event);
|
case LogEvent.ANNOTATE_ROWS_EVENT:
|
||||||
// break;
|
parseAnnotateRowsEvent((AnnotateRowsEvent) event);
|
||||||
// case LogEvent.ROWS_QUERY_LOG_EVENT:
|
break;
|
||||||
// parseRowsQueryEvent((RowsQueryLogEvent) event);
|
case LogEvent.XID_EVENT:
|
||||||
// break;
|
parseXidEvent((XidLogEvent) event);
|
||||||
// case LogEvent.ANNOTATE_ROWS_EVENT:
|
break;
|
||||||
// parseAnnotateRowsEvent((AnnotateRowsEvent) event);
|
default:
|
||||||
// break;
|
break;
|
||||||
// case LogEvent.XID_EVENT:
|
}
|
||||||
// parseXidEvent((XidLogEvent) event);
|
|
||||||
// break;
|
|
||||||
// default:
|
|
||||||
// break;
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
<artifactId>canal</artifactId>
|
<artifactId>canal</artifactId>
|
||||||
<version>1.1.1-SNAPSHOT</version>
|
<version>1.1.1</version>
|
||||||
<relativePath>../pom.xml</relativePath>
|
<relativePath>../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
<groupId>com.alibaba.otter</groupId>
|
<groupId>com.alibaba.otter</groupId>
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
<exclude>**/canal.properties</exclude>
|
<exclude>**/canal.properties</exclude>
|
||||||
<exclude>**/spring/**</exclude>
|
<exclude>**/spring/**</exclude>
|
||||||
<exclude>**/example/**</exclude>
|
<exclude>**/example/**</exclude>
|
||||||
<exclude>**/kafka.yml</exclude>
|
<exclude>**/mq.yml</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|||||||
@@ -387,7 +387,7 @@ public class CanalController {
|
|||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getProperty(Properties properties, String key) {
|
public static String getProperty(Properties properties, String key) {
|
||||||
key = StringUtils.trim(key);
|
key = StringUtils.trim(key);
|
||||||
String value = System.getProperty(key);
|
String value = System.getProperty(key);
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import org.apache.commons.lang.StringUtils;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import com.alibaba.otter.canal.kafka.CanalKafkaStarter;
|
import com.alibaba.otter.canal.kafka.CanalKafkaProducer;
|
||||||
import com.alibaba.otter.canal.server.CanalServerStarter;
|
import com.alibaba.otter.canal.rocketmq.CanalRocketMQProducer;
|
||||||
|
import com.alibaba.otter.canal.server.CanalMQStarter;
|
||||||
|
import com.alibaba.otter.canal.spi.CanalMQProducer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* canal独立版本启动的入口类
|
* canal独立版本启动的入口类
|
||||||
@@ -36,6 +38,19 @@ public class CanalLauncher {
|
|||||||
properties.load(new FileInputStream(conf));
|
properties.load(new FileInputStream(conf));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CanalMQProducer canalMQProducer = null;
|
||||||
|
String serverMode = CanalController.getProperty(properties, CanalConstants.CANAL_SERVER_MODE);
|
||||||
|
if (serverMode.equalsIgnoreCase("kafka")) {
|
||||||
|
canalMQProducer = new CanalKafkaProducer();
|
||||||
|
} else if (serverMode.equalsIgnoreCase("rocketmq")) {
|
||||||
|
canalMQProducer = new CanalRocketMQProducer();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (canalMQProducer != null) {
|
||||||
|
// disable netty
|
||||||
|
System.setProperty(CanalConstants.CANAL_WITHOUT_NETTY, "true");
|
||||||
|
}
|
||||||
|
|
||||||
logger.info("## start the canal server.");
|
logger.info("## start the canal server.");
|
||||||
final CanalController controller = new CanalController(properties);
|
final CanalController controller = new CanalController(properties);
|
||||||
controller.start();
|
controller.start();
|
||||||
@@ -55,17 +70,12 @@ public class CanalLauncher {
|
|||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
CanalServerStarter canalServerStarter = null;
|
if (canalMQProducer != null) {
|
||||||
String serverMode = controller.getProperty(properties, CanalConstants.CANAL_SERVER_MODE);
|
CanalMQStarter canalServerStarter = new CanalMQStarter(canalMQProducer);
|
||||||
if (serverMode.equalsIgnoreCase("kafka")) {
|
|
||||||
canalServerStarter = new CanalKafkaStarter();
|
|
||||||
} else if (serverMode.equalsIgnoreCase("rocketMQ")) {
|
|
||||||
// 预留rocketMQ启动
|
|
||||||
}
|
|
||||||
|
|
||||||
if (canalServerStarter != null) {
|
if (canalServerStarter != null) {
|
||||||
canalServerStarter.init();
|
canalServerStarter.init();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
logger.error("## Something goes wrong when starting up the canal Server:", e);
|
logger.error("## Something goes wrong when starting up the canal Server:", e);
|
||||||
System.exit(0);
|
System.exit(0);
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ canal.zkServers=
|
|||||||
# flush data to zk
|
# flush data to zk
|
||||||
canal.zookeeper.flush.period = 1000
|
canal.zookeeper.flush.period = 1000
|
||||||
canal.withoutNetty = false
|
canal.withoutNetty = false
|
||||||
# tcp, kafka, rocketMQ
|
# tcp, kafka, RocketMQ
|
||||||
canal.serverMode = tcp
|
canal.serverMode = tcp
|
||||||
# flush meta cursor/parse position to file
|
# flush meta cursor/parse position to file
|
||||||
canal.file.data.dir = ${canal.conf.dir}
|
canal.file.data.dir = ${canal.conf.dir}
|
||||||
@@ -20,6 +20,7 @@ canal.instance.memory.buffer.size = 16384
|
|||||||
canal.instance.memory.buffer.memunit = 1024
|
canal.instance.memory.buffer.memunit = 1024
|
||||||
## meory store gets mode used MEMSIZE or ITEMSIZE
|
## meory store gets mode used MEMSIZE or ITEMSIZE
|
||||||
canal.instance.memory.batch.mode = MEMSIZE
|
canal.instance.memory.batch.mode = MEMSIZE
|
||||||
|
canal.instance.memory.rawEntry = true
|
||||||
|
|
||||||
## detecing config
|
## detecing config
|
||||||
canal.instance.detecting.enable = false
|
canal.instance.detecting.enable = false
|
||||||
@@ -68,6 +69,10 @@ canal.instance.tsdb.dir=${canal.file.data.dir:../conf}/${canal.instance.destinat
|
|||||||
canal.instance.tsdb.url=jdbc:h2:${canal.instance.tsdb.dir}/h2;CACHE_SIZE=1000;MODE=MYSQL;
|
canal.instance.tsdb.url=jdbc:h2:${canal.instance.tsdb.dir}/h2;CACHE_SIZE=1000;MODE=MYSQL;
|
||||||
canal.instance.tsdb.dbUsername=canal
|
canal.instance.tsdb.dbUsername=canal
|
||||||
canal.instance.tsdb.dbPassword=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
|
||||||
|
|
||||||
# rds oss binlog account
|
# rds oss binlog account
|
||||||
canal.instance.rds.accesskey =
|
canal.instance.rds.accesskey =
|
||||||
|
|||||||
@@ -31,8 +31,12 @@ canal.instance.tsdb.enable=true
|
|||||||
|
|
||||||
# username/password
|
# username/password
|
||||||
canal.instance.dbUsername=canal
|
canal.instance.dbUsername=canal
|
||||||
canal.instance.dbPassword=canal
|
canal.instance.dbPassword=cZozNf1mzW6EQLGO2q9u99619xbZLO0fbua3EX08r4BWNXb8lAt1aHrTEOBttd6UY8Vnuc0easlVXZDdLtt8BQ==
|
||||||
|
canal.instance.pwdPublicKey=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALK4BUxdDltRRE5/zXpVEVPUgunvscYFtEip3pmLlhrWpacX7y7GCMo2/JM6LeHmiiNdH1FWgGCpUfircSwlWKUCAwEAAQ==
|
||||||
canal.instance.connectionCharset = UTF-8
|
canal.instance.connectionCharset = UTF-8
|
||||||
|
canal.instance.defaultDatabaseName =test
|
||||||
|
# enable druid Decrypt database password
|
||||||
|
canal.instance.enableDruid=true
|
||||||
|
|
||||||
# table regex
|
# table regex
|
||||||
canal.instance.filter.regex=.*\\..*
|
canal.instance.filter.regex=.*\\..*
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
servers: slave1:6667,slave2:6667,slave3:6667
|
|
||||||
retries: 0
|
|
||||||
batchSize: 16384
|
|
||||||
lingerMs: 1
|
|
||||||
bufferMemory: 33554432
|
|
||||||
|
|
||||||
# Canal的batch size, 默认50K, 由于kafka最大消息体限制请勿超过1M(900K以下)
|
|
||||||
canalBatchSize: 50
|
|
||||||
# Canal get数据的超时时间, 单位: 毫秒, 空为不限超时
|
|
||||||
canalGetTimeout: 100
|
|
||||||
|
|
||||||
canalDestinations:
|
|
||||||
- canalDestination: example
|
|
||||||
topic: example
|
|
||||||
partition:
|
|
||||||
@@ -79,7 +79,7 @@
|
|||||||
</logger>
|
</logger>
|
||||||
|
|
||||||
<root level="WARN">
|
<root level="WARN">
|
||||||
<!-- <appender-ref ref="STDOUT"/> -->
|
<appender-ref ref="STDOUT"/>
|
||||||
<appender-ref ref="CANAL-ROOT" />
|
<appender-ref ref="CANAL-ROOT" />
|
||||||
</root>
|
</root>
|
||||||
</configuration>
|
</configuration>
|
||||||
@@ -1,4 +1,34 @@
|
|||||||
{
|
{
|
||||||
|
"__inputs": [
|
||||||
|
{
|
||||||
|
"name": "DS_PROMETHEUS",
|
||||||
|
"label": "prometheus",
|
||||||
|
"description": "",
|
||||||
|
"type": "datasource",
|
||||||
|
"pluginId": "prometheus",
|
||||||
|
"pluginName": "Prometheus"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"__requires": [
|
||||||
|
{
|
||||||
|
"type": "grafana",
|
||||||
|
"id": "grafana",
|
||||||
|
"name": "Grafana",
|
||||||
|
"version": "5.2.2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "panel",
|
||||||
|
"id": "graph",
|
||||||
|
"name": "Graph",
|
||||||
|
"version": "5.0.0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "datasource",
|
||||||
|
"id": "prometheus",
|
||||||
|
"name": "Prometheus",
|
||||||
|
"version": "5.0.0"
|
||||||
|
}
|
||||||
|
],
|
||||||
"annotations": {
|
"annotations": {
|
||||||
"list": [
|
"list": [
|
||||||
{
|
{
|
||||||
@@ -15,8 +45,8 @@
|
|||||||
"editable": true,
|
"editable": true,
|
||||||
"gnetId": null,
|
"gnetId": null,
|
||||||
"graphTooltip": 0,
|
"graphTooltip": 0,
|
||||||
"id": 8,
|
"id": null,
|
||||||
"iteration": 1534740332233,
|
"iteration": 1536989235272,
|
||||||
"links": [],
|
"links": [],
|
||||||
"panels": [
|
"panels": [
|
||||||
{
|
{
|
||||||
@@ -189,7 +219,7 @@
|
|||||||
"steppedLine": false,
|
"steppedLine": false,
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"expr": "rate(canal_instance_received_binlog_bytes{destination=~\"$destination\"}[2m]) / 1024",
|
"expr": "rate(canal_instance_received_binlog_bytes{destination=~\"$destination\", parser=\"0\"}[2m]) / 1024",
|
||||||
"format": "time_series",
|
"format": "time_series",
|
||||||
"interval": "15s",
|
"interval": "15s",
|
||||||
"intervalFactor": 2,
|
"intervalFactor": 2,
|
||||||
@@ -203,6 +233,22 @@
|
|||||||
"intervalFactor": 2,
|
"intervalFactor": 2,
|
||||||
"legendFormat": "outbound",
|
"legendFormat": "outbound",
|
||||||
"refId": "B"
|
"refId": "B"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expr": "rate(canal_instance_received_binlog_bytes{destination=~\"$destination\", parser=\"1\"}[2m]) / 1024",
|
||||||
|
"format": "time_series",
|
||||||
|
"interval": "15s",
|
||||||
|
"intervalFactor": 2,
|
||||||
|
"legendFormat": "inbound-1",
|
||||||
|
"refId": "C"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expr": "rate(canal_instance_received_binlog_bytes{destination=~\"$destination\", parser=\"2\"}[2m]) / 1024",
|
||||||
|
"format": "time_series",
|
||||||
|
"interval": "15s",
|
||||||
|
"intervalFactor": 2,
|
||||||
|
"legendFormat": "inbound-2",
|
||||||
|
"refId": "D"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thresholds": [],
|
"thresholds": [],
|
||||||
@@ -399,20 +445,36 @@
|
|||||||
"steppedLine": false,
|
"steppedLine": false,
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"expr": "clamp_max(rate(canal_instance_sink_blocking_time{destination=~\"$destination\"}[2m]), 1000) / 10",
|
"expr": "clamp_max(rate(canal_instance_publish_blocking_time{destination=~\"$destination\", parser=\"0\"}[2m]), 1000) / 10",
|
||||||
"format": "time_series",
|
"format": "time_series",
|
||||||
"interval": "15s",
|
"interval": "15s",
|
||||||
"intervalFactor": 2,
|
"intervalFactor": 2,
|
||||||
"legendFormat": "dump",
|
"legendFormat": "dump",
|
||||||
"refId": "A"
|
"refId": "B"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"expr": "clamp_max(rate(canal_instance_publish_blocking_time{destination=~\"$destination\"}[2m]), 1000) / 10",
|
"expr": "clamp_max(rate(canal_instance_sink_blocking_time{destination=~\"$destination\"}[2m]), 1000) / 10",
|
||||||
"format": "time_series",
|
"format": "time_series",
|
||||||
"interval": "15s",
|
"interval": "15s",
|
||||||
"intervalFactor": 2,
|
"intervalFactor": 2,
|
||||||
"legendFormat": "sink",
|
"legendFormat": "sink",
|
||||||
"refId": "B"
|
"refId": "A"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expr": "clamp_max(rate(canal_instance_publish_blocking_time{destination=~\"$destination\", parser=\"1\"}[2m]), 1000) / 10",
|
||||||
|
"format": "time_series",
|
||||||
|
"interval": "15s",
|
||||||
|
"intervalFactor": 2,
|
||||||
|
"legendFormat": "dump-1",
|
||||||
|
"refId": "C"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expr": "clamp_max(rate(canal_instance_publish_blocking_time{destination=~\"$destination\", parser=\"2\"}[2m]), 1000) / 10",
|
||||||
|
"format": "time_series",
|
||||||
|
"interval": "15s",
|
||||||
|
"intervalFactor": 2,
|
||||||
|
"legendFormat": "dump-2",
|
||||||
|
"refId": "D"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"thresholds": [],
|
"thresholds": [],
|
||||||
@@ -465,7 +527,7 @@
|
|||||||
},
|
},
|
||||||
"id": 32,
|
"id": 32,
|
||||||
"panels": [],
|
"panels": [],
|
||||||
"title": "Server",
|
"title": "Throughput",
|
||||||
"type": "row"
|
"type": "row"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -660,180 +722,6 @@
|
|||||||
"alignLevel": null
|
"alignLevel": null
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"aliasColors": {},
|
|
||||||
"bars": false,
|
|
||||||
"dashLength": 10,
|
|
||||||
"dashes": false,
|
|
||||||
"datasource": "$datasource",
|
|
||||||
"description": "Canal instance ringbuffer内未释放的events数量。",
|
|
||||||
"fill": 1,
|
|
||||||
"gridPos": {
|
|
||||||
"h": 5,
|
|
||||||
"w": 6,
|
|
||||||
"x": 12,
|
|
||||||
"y": 7
|
|
||||||
},
|
|
||||||
"id": 20,
|
|
||||||
"legend": {
|
|
||||||
"avg": false,
|
|
||||||
"current": false,
|
|
||||||
"max": false,
|
|
||||||
"min": false,
|
|
||||||
"show": true,
|
|
||||||
"total": false,
|
|
||||||
"values": false
|
|
||||||
},
|
|
||||||
"lines": true,
|
|
||||||
"linewidth": 1,
|
|
||||||
"links": [],
|
|
||||||
"nullPointMode": "null",
|
|
||||||
"percentage": false,
|
|
||||||
"pointradius": 5,
|
|
||||||
"points": false,
|
|
||||||
"renderer": "flot",
|
|
||||||
"seriesOverrides": [],
|
|
||||||
"spaceLength": 10,
|
|
||||||
"stack": false,
|
|
||||||
"steppedLine": false,
|
|
||||||
"targets": [
|
|
||||||
{
|
|
||||||
"expr": "canal_instance_store_produce_seq{destination=~\"$destination\"} - canal_instance_store_consume_seq{destination=~\"$destination\"}",
|
|
||||||
"format": "time_series",
|
|
||||||
"interval": "15s",
|
|
||||||
"intervalFactor": 2,
|
|
||||||
"legendFormat": "events",
|
|
||||||
"refId": "A"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"thresholds": [],
|
|
||||||
"timeFrom": null,
|
|
||||||
"timeShift": null,
|
|
||||||
"title": "Store remain events",
|
|
||||||
"tooltip": {
|
|
||||||
"shared": true,
|
|
||||||
"sort": 0,
|
|
||||||
"value_type": "individual"
|
|
||||||
},
|
|
||||||
"type": "graph",
|
|
||||||
"xaxis": {
|
|
||||||
"buckets": null,
|
|
||||||
"mode": "time",
|
|
||||||
"name": null,
|
|
||||||
"show": true,
|
|
||||||
"values": []
|
|
||||||
},
|
|
||||||
"yaxes": [
|
|
||||||
{
|
|
||||||
"decimals": null,
|
|
||||||
"format": "none",
|
|
||||||
"label": "",
|
|
||||||
"logBase": 1,
|
|
||||||
"max": null,
|
|
||||||
"min": null,
|
|
||||||
"show": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"decimals": null,
|
|
||||||
"format": "short",
|
|
||||||
"label": null,
|
|
||||||
"logBase": 1,
|
|
||||||
"max": null,
|
|
||||||
"min": null,
|
|
||||||
"show": true
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"yaxis": {
|
|
||||||
"align": false,
|
|
||||||
"alignLevel": null
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"aliasColors": {},
|
|
||||||
"bars": false,
|
|
||||||
"dashLength": 10,
|
|
||||||
"dashes": false,
|
|
||||||
"datasource": "$datasource",
|
|
||||||
"description": "Canal instance ringbuffer 内未释放events占用内存。",
|
|
||||||
"fill": 1,
|
|
||||||
"gridPos": {
|
|
||||||
"h": 5,
|
|
||||||
"w": 6,
|
|
||||||
"x": 18,
|
|
||||||
"y": 7
|
|
||||||
},
|
|
||||||
"id": 22,
|
|
||||||
"legend": {
|
|
||||||
"avg": false,
|
|
||||||
"current": false,
|
|
||||||
"max": false,
|
|
||||||
"min": false,
|
|
||||||
"show": true,
|
|
||||||
"total": false,
|
|
||||||
"values": false
|
|
||||||
},
|
|
||||||
"lines": true,
|
|
||||||
"linewidth": 1,
|
|
||||||
"links": [],
|
|
||||||
"nullPointMode": "null",
|
|
||||||
"percentage": false,
|
|
||||||
"pointradius": 5,
|
|
||||||
"points": false,
|
|
||||||
"renderer": "flot",
|
|
||||||
"seriesOverrides": [],
|
|
||||||
"spaceLength": 10,
|
|
||||||
"stack": false,
|
|
||||||
"steppedLine": false,
|
|
||||||
"targets": [
|
|
||||||
{
|
|
||||||
"expr": "(canal_instance_store_produce_mem{destination=~\"$destination\"} - canal_instance_store_consume_mem{destination=~\"$destination\"}) / 1024",
|
|
||||||
"format": "time_series",
|
|
||||||
"interval": "15s",
|
|
||||||
"intervalFactor": 2,
|
|
||||||
"legendFormat": "memsize",
|
|
||||||
"refId": "A"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"thresholds": [],
|
|
||||||
"timeFrom": null,
|
|
||||||
"timeShift": null,
|
|
||||||
"title": "Store remain mem",
|
|
||||||
"tooltip": {
|
|
||||||
"shared": true,
|
|
||||||
"sort": 0,
|
|
||||||
"value_type": "individual"
|
|
||||||
},
|
|
||||||
"type": "graph",
|
|
||||||
"xaxis": {
|
|
||||||
"buckets": null,
|
|
||||||
"mode": "time",
|
|
||||||
"name": null,
|
|
||||||
"show": true,
|
|
||||||
"values": []
|
|
||||||
},
|
|
||||||
"yaxes": [
|
|
||||||
{
|
|
||||||
"format": "deckbytes",
|
|
||||||
"label": null,
|
|
||||||
"logBase": 1,
|
|
||||||
"max": null,
|
|
||||||
"min": null,
|
|
||||||
"show": true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"format": "short",
|
|
||||||
"label": null,
|
|
||||||
"logBase": 1,
|
|
||||||
"max": null,
|
|
||||||
"min": null,
|
|
||||||
"show": true
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"yaxis": {
|
|
||||||
"align": false,
|
|
||||||
"alignLevel": null
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"collapsed": false,
|
"collapsed": false,
|
||||||
"gridPos": {
|
"gridPos": {
|
||||||
@@ -938,7 +826,7 @@
|
|||||||
"bars": false,
|
"bars": false,
|
||||||
"dashLength": 10,
|
"dashLength": 10,
|
||||||
"dashes": false,
|
"dashes": false,
|
||||||
"datasource": "$datasource",
|
"datasource": "${DS_PROMETHEUS}",
|
||||||
"description": "client 请求的GET与ACK包的QPS。",
|
"description": "client 请求的GET与ACK包的QPS。",
|
||||||
"fill": 1,
|
"fill": 1,
|
||||||
"gridPos": {
|
"gridPos": {
|
||||||
@@ -1218,6 +1106,193 @@
|
|||||||
"align": false,
|
"align": false,
|
||||||
"alignLevel": null
|
"alignLevel": null
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"collapsed": false,
|
||||||
|
"gridPos": {
|
||||||
|
"h": 1,
|
||||||
|
"w": 24,
|
||||||
|
"x": 0,
|
||||||
|
"y": 18
|
||||||
|
},
|
||||||
|
"id": 36,
|
||||||
|
"panels": [],
|
||||||
|
"title": "Store",
|
||||||
|
"type": "row"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"aliasColors": {},
|
||||||
|
"bars": false,
|
||||||
|
"dashLength": 10,
|
||||||
|
"dashes": false,
|
||||||
|
"datasource": "$datasource",
|
||||||
|
"description": "Canal instance ringbuffer内未释放的events数量。",
|
||||||
|
"fill": 1,
|
||||||
|
"gridPos": {
|
||||||
|
"h": 5,
|
||||||
|
"w": 6,
|
||||||
|
"x": 0,
|
||||||
|
"y": 19
|
||||||
|
},
|
||||||
|
"id": 20,
|
||||||
|
"legend": {
|
||||||
|
"avg": false,
|
||||||
|
"current": false,
|
||||||
|
"max": false,
|
||||||
|
"min": false,
|
||||||
|
"show": true,
|
||||||
|
"total": false,
|
||||||
|
"values": false
|
||||||
|
},
|
||||||
|
"lines": true,
|
||||||
|
"linewidth": 1,
|
||||||
|
"links": [],
|
||||||
|
"nullPointMode": "null",
|
||||||
|
"percentage": false,
|
||||||
|
"pointradius": 5,
|
||||||
|
"points": false,
|
||||||
|
"renderer": "flot",
|
||||||
|
"seriesOverrides": [],
|
||||||
|
"spaceLength": 10,
|
||||||
|
"stack": false,
|
||||||
|
"steppedLine": false,
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "canal_instance_store_produce_seq{destination=~\"$destination\"} - canal_instance_store_consume_seq{destination=~\"$destination\"}",
|
||||||
|
"format": "time_series",
|
||||||
|
"interval": "15s",
|
||||||
|
"intervalFactor": 2,
|
||||||
|
"legendFormat": "events",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"thresholds": [],
|
||||||
|
"timeFrom": null,
|
||||||
|
"timeShift": null,
|
||||||
|
"title": "Store remain events",
|
||||||
|
"tooltip": {
|
||||||
|
"shared": true,
|
||||||
|
"sort": 0,
|
||||||
|
"value_type": "individual"
|
||||||
|
},
|
||||||
|
"type": "graph",
|
||||||
|
"xaxis": {
|
||||||
|
"buckets": null,
|
||||||
|
"mode": "time",
|
||||||
|
"name": null,
|
||||||
|
"show": true,
|
||||||
|
"values": []
|
||||||
|
},
|
||||||
|
"yaxes": [
|
||||||
|
{
|
||||||
|
"decimals": null,
|
||||||
|
"format": "none",
|
||||||
|
"label": "",
|
||||||
|
"logBase": 1,
|
||||||
|
"max": null,
|
||||||
|
"min": null,
|
||||||
|
"show": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"decimals": null,
|
||||||
|
"format": "short",
|
||||||
|
"label": null,
|
||||||
|
"logBase": 1,
|
||||||
|
"max": null,
|
||||||
|
"min": null,
|
||||||
|
"show": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"yaxis": {
|
||||||
|
"align": false,
|
||||||
|
"alignLevel": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"aliasColors": {},
|
||||||
|
"bars": false,
|
||||||
|
"dashLength": 10,
|
||||||
|
"dashes": false,
|
||||||
|
"datasource": "$datasource",
|
||||||
|
"description": "Canal instance ringbuffer 内未释放events占用内存。",
|
||||||
|
"fill": 1,
|
||||||
|
"gridPos": {
|
||||||
|
"h": 5,
|
||||||
|
"w": 6,
|
||||||
|
"x": 6,
|
||||||
|
"y": 19
|
||||||
|
},
|
||||||
|
"id": 22,
|
||||||
|
"legend": {
|
||||||
|
"avg": false,
|
||||||
|
"current": false,
|
||||||
|
"max": false,
|
||||||
|
"min": false,
|
||||||
|
"show": true,
|
||||||
|
"total": false,
|
||||||
|
"values": false
|
||||||
|
},
|
||||||
|
"lines": true,
|
||||||
|
"linewidth": 1,
|
||||||
|
"links": [],
|
||||||
|
"nullPointMode": "null",
|
||||||
|
"percentage": false,
|
||||||
|
"pointradius": 5,
|
||||||
|
"points": false,
|
||||||
|
"renderer": "flot",
|
||||||
|
"seriesOverrides": [],
|
||||||
|
"spaceLength": 10,
|
||||||
|
"stack": false,
|
||||||
|
"steppedLine": false,
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "(canal_instance_store_produce_mem{destination=~\"$destination\"} - canal_instance_store_consume_mem{destination=~\"$destination\"}) / 1024",
|
||||||
|
"format": "time_series",
|
||||||
|
"interval": "15s",
|
||||||
|
"intervalFactor": 2,
|
||||||
|
"legendFormat": "memsize",
|
||||||
|
"refId": "A"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"thresholds": [],
|
||||||
|
"timeFrom": null,
|
||||||
|
"timeShift": null,
|
||||||
|
"title": "Store remain mem",
|
||||||
|
"tooltip": {
|
||||||
|
"shared": true,
|
||||||
|
"sort": 0,
|
||||||
|
"value_type": "individual"
|
||||||
|
},
|
||||||
|
"type": "graph",
|
||||||
|
"xaxis": {
|
||||||
|
"buckets": null,
|
||||||
|
"mode": "time",
|
||||||
|
"name": null,
|
||||||
|
"show": true,
|
||||||
|
"values": []
|
||||||
|
},
|
||||||
|
"yaxes": [
|
||||||
|
{
|
||||||
|
"format": "deckbytes",
|
||||||
|
"label": null,
|
||||||
|
"logBase": 1,
|
||||||
|
"max": null,
|
||||||
|
"min": null,
|
||||||
|
"show": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"format": "short",
|
||||||
|
"label": null,
|
||||||
|
"logBase": 1,
|
||||||
|
"max": null,
|
||||||
|
"min": null,
|
||||||
|
"show": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"yaxis": {
|
||||||
|
"align": false,
|
||||||
|
"alignLevel": null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"refresh": false,
|
"refresh": false,
|
||||||
@@ -1230,9 +1305,8 @@
|
|||||||
"list": [
|
"list": [
|
||||||
{
|
{
|
||||||
"current": {
|
"current": {
|
||||||
"tags": [],
|
"text": "prometheus",
|
||||||
"text": "Prometheus",
|
"value": "prometheus"
|
||||||
"value": "Prometheus"
|
|
||||||
},
|
},
|
||||||
"hide": 0,
|
"hide": 0,
|
||||||
"label": "datasource",
|
"label": "datasource",
|
||||||
@@ -1245,10 +1319,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"allValue": null,
|
"allValue": null,
|
||||||
"current": {
|
"current": {},
|
||||||
"text": "example",
|
|
||||||
"value": "example"
|
|
||||||
},
|
|
||||||
"datasource": "$datasource",
|
"datasource": "$datasource",
|
||||||
"hide": 0,
|
"hide": 0,
|
||||||
"includeAll": false,
|
"includeAll": false,
|
||||||
@@ -1269,7 +1340,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"time": {
|
"time": {
|
||||||
"from": "now-1h",
|
"from": "now-6h",
|
||||||
"to": "now"
|
"to": "now"
|
||||||
},
|
},
|
||||||
"timepicker": {
|
"timepicker": {
|
||||||
@@ -1300,5 +1371,5 @@
|
|||||||
"timezone": "",
|
"timezone": "",
|
||||||
"title": "Canal instances",
|
"title": "Canal instances",
|
||||||
"uid": "8vh8NGpiz",
|
"uid": "8vh8NGpiz",
|
||||||
"version": 1
|
"version": 103
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user