提交 | 用户 | age
|
0b055a
|
1 |
package com.hz.canal.starter.container; |
R |
2 |
|
|
3 |
import com.alibaba.otter.canal.protocol.CanalEntry; |
|
4 |
import com.hz.canal.starter.listener.ApplicationReadyListener; |
|
5 |
import org.springframework.context.SmartLifecycle; |
|
6 |
|
|
7 |
import java.util.Arrays; |
|
8 |
import java.util.List; |
|
9 |
import java.util.concurrent.TimeUnit; |
|
10 |
|
|
11 |
/** |
|
12 |
* 抽象的canal transponder ,实现SmartLifecycle接口,声明周期由spring进行管理 |
|
13 |
* |
|
14 |
* @author wuqiong 2022/4/11 |
|
15 |
*/ |
|
16 |
public abstract class AbstractCanalTransponderContainer implements SmartLifecycle { |
|
17 |
protected boolean isRunning = false; |
|
18 |
protected final Long SLEEP_TIME_MILLI_SECONDS = 1000L; |
|
19 |
protected List<CanalEntry.EntryType> IGNORE_ENTRY_TYPES = |
|
20 |
Arrays.asList(CanalEntry.EntryType.TRANSACTIONBEGIN, |
|
21 |
CanalEntry.EntryType.TRANSACTIONEND, |
|
22 |
CanalEntry.EntryType.HEARTBEAT); |
|
23 |
|
|
24 |
protected abstract void doStart(); |
|
25 |
|
|
26 |
protected abstract void initConnect(); |
|
27 |
|
|
28 |
protected abstract void disconnect(); |
|
29 |
|
|
30 |
|
|
31 |
@Override |
|
32 |
public void start() { |
|
33 |
new Thread(() -> { |
|
34 |
// spring 启动后 才会进行canal数据拉取 |
|
35 |
while (!ApplicationReadyListener.START_LISTENER_CONTAINER.get()) |
|
36 |
sleep(5L * SLEEP_TIME_MILLI_SECONDS); |
|
37 |
initConnect(); |
|
38 |
while (isRunning() && !Thread.currentThread().isInterrupted()) doStart(); |
|
39 |
disconnect(); // 线程被终止或者容器已经停止,需要关闭连接 |
|
40 |
}).start(); |
|
41 |
setRunning(true); |
|
42 |
} |
|
43 |
|
|
44 |
@Override |
|
45 |
public void stop() { |
|
46 |
setRunning(false); |
|
47 |
} |
|
48 |
|
|
49 |
@Override |
|
50 |
public void stop(Runnable callback) { |
|
51 |
callback.run(); |
|
52 |
setRunning(false); |
|
53 |
sleep(SLEEP_TIME_MILLI_SECONDS); |
|
54 |
} |
|
55 |
|
|
56 |
@Override |
|
57 |
public boolean isRunning() { |
|
58 |
return isRunning; |
|
59 |
} |
|
60 |
|
|
61 |
protected void setRunning(boolean bool) { |
|
62 |
isRunning = bool; |
|
63 |
} |
|
64 |
|
|
65 |
protected void sleep(long sleepTimeMilliSeconds) { |
|
66 |
try { |
|
67 |
TimeUnit.MILLISECONDS.sleep(sleepTimeMilliSeconds); |
|
68 |
if (!isRunning()) Thread.currentThread().interrupt(); |
|
69 |
} catch (InterruptedException e) { |
|
70 |
} |
|
71 |
} |
|
72 |
|
|
73 |
|
|
74 |
} |