Pekko 网关设计

需要 Stream 相关知识点: pekko-stream

简单来说就是如果涉及到大规模的消息交换, 最好实现 Source → Flow → Sink 的 inbound/outbound 双端队列

pekko 内部已经实现简单的数据交换分帧功能, 结合起来就可以构建自己的网关服务, 先简单引入必须要的依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- Pekko 网关基础依赖, 其他版本和 Scala 按照官网来选择  -->
<dependencies>

<dependency>
<groupId>org.apache.pekko</groupId>
<artifactId>pekko-actor-typed_${pekko.scala.binary.version}</artifactId>
</dependency>

<dependency>
<groupId>org.apache.pekko</groupId>
<artifactId>pekko-stream-typed_${pekko.scala.binary.version}</artifactId>
</dependency>
</dependencies>

我先在测试单元当中实现自己的网关, 后面才开始抽离出通用模式 (这里引用 Quarkus 框架做底层容器集成)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import me.meteorcat.chorus.common.actor.ActorConfig;
import org.jboss.logging.Logger;

/**
* 网络交换 - 怎么去设计网关
*/
@QuarkusTest
public class TcpBehaviorTest {

/**
* 日志对象
*/
final Logger logger = Logger.getLogger(TcpBehaviorTest.class);

/**
* Actor 系统配置
*/
@Inject
ActorConfig actorConfig;

}

以此基础来讲解和设计整体框架, 这里面涉及到 Flow (双端数据交换) 概念必须要提前了解

协议定义

注意: 这部分是最复杂和最容易出错的地方 (甚至 AI 辅助解释都会出问题), 所以尽量查询官方文档和样例去理解这部分内容

这里采用 Pekko 内置的 Framing.simpleFramingProtocol 功能构建网络传输层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
TCP 字节流
│
▼
┌───────────────────────────
│ 传输分帧层 |BidiFlow: 处理 TCP 数据拆包问题
│ simpleFramingProtocol
└───────────────────────────
│ 负载字节(协议ID+消息体)
▼
┌───────────────────────────
│ 协议编解码层 |BidiFlow: 字节 ↔ 业务消息信封
│ 解析协议ID + 消息体
└───────────────────────────
│ 业务消息对象
▼
┌───────────────────────────
│ 业务路由层 |Flow/BidiFlow: 业务逻辑处理
│ 按协议ID路由到 Actor
└───────────────────────────

Framing.simpleFramingProtocol(maxMessageLength) 生成的 BidiFlow 专门处理最外层的长度分帧,它的双向端口语义非常明确:

端口 方向 输入 输出 说明
RX(接收端) 入站 Inbound 原始 TCP 字节流 去掉长度字段的完整负载 自动处理拆包、超长帧截断
TX(发送端) 出站 Outbound 业务负载字节 加上 4 字节大端长度的完整帧 自动计算长度并封帧

对应你代码里的 BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed>:

  • 左入站: ByteString(原始字节)→ 左出站: ByteString(协议ID+消息体负载)

  • 右入站: ByteString(业务响应负载)→ 右出站: ByteString(带长度的完整帧)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* 网络交换 - 怎么去设计网关
*/
@QuarkusTest
public class TcpBehaviorTest {
// 其他略

/**
* 交换协议数据
*/
@Test
void protocol() throws ExecutionException, InterruptedException {
// 构建 Actor 系统
ActorSystem<Void> system = actorConfig.build((ActorContext<Void> ignore) -> {

}, this.actorConfig.load());


// 一般来说, 客户端提交的数据格式都是按照以下格式提交
// [int32:数据长度] [int32:协议ID] [byte[]:消息主体]
// 按照协议ID来最终确定功能类选用序列化处理再推送到对应 Actor
// 这部分 Pekko 已经帮我们规划好了, 内置 Framing.simpleFramingProtocol 处理双端消息处理
// 构建方式如下, 注意返回值是 BidiFlow<>, Bidi 代表光纤的双线模块, 涵盖有 TX(发射端口)/RX(接收端口), 用在这里是挺不错
final int maximumMessageLength = 1 << 20; // 最大的 1M 数据量
final BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> bidiFlow =
Framing.simpleFramingProtocol(maximumMessageLength);
// 注意: BidiFlow<> 只是构建消息处理通道(相当于创建过滤器), 后面还需要自己接入输入端和输出端


// 目前大部分情况都是采用 Protobuf 序列化之后提交上来对应的 id + 消息
// 这里先展示怎么直接数据投递处理, 结合 Source → Flow → Sink 来查看数据交换过程

// 构建自定义 1001 协议数据
ByteString proto1001Message = ByteString
.createBuilder()
.putInt(1001, ByteOrder.BIG_ENDIAN) // 写入大端网络序的协议ID
.append(ByteString.fromString("Hello.Protobuf-1001")) // 写入消息结构内容
.result(); // 获取消息包数据
logger.infof("proto message 1001 = %s", Arrays.toString(proto1001Message.toArray()));

// 打包成 simpleFramingProtocol 消息
ByteString proto1001Frame = ByteString
.createBuilder()
.putInt(proto1001Message.size(), ByteOrder.BIG_ENDIAN) // 将协议长度和消息内容打包
.append(proto1001Message)
.result();
logger.infof("proto frame 1001 = %s", Arrays.toString(proto1001Frame.toArray()));


// 构建中间处理器, 也就是 BidiFlow 之后拆分出来的 message
Flow<ByteString, ByteString, NotUsed> businessFlow = Flow.of(ByteString.class).map(payload -> {
// 这里的 payload 已经经过 BidiFlow 处理了, payload 已去掉长度前缀
final ByteIterator it = payload.iterator(); // 数据迭代器
int id = it.getInt(ByteOrder.BIG_ENDIAN); // 以网络序列提取 int, 也就是获取协议ID
final ByteString body = it.toByteString(); // 提取剩余的的字节数据
logger.infof("decode message: id = %d, bytes = %s", id, Arrays.toString(body.toArray()));
return body; // 打包移交下个处理器
});

// 核心处理, reversed 反转依赖, 将业务 flow 转为处理端
Flow<ByteString, ByteString, NotUsed> businessHandler = bidiFlow.reversed().join(businessFlow);

// 将业务的解码数据处理器接入到 Source 当中
ByteString outputFrame = Source.single(proto1001Frame)
.via(businessHandler)
// Sink.head() 代表从消息队列头将数据提取, 长连接、持续数据流不能用 head, 而是应该用 Sink.foreach、Sink.actorRef
.runWith(Sink.head(), system)
.toCompletableFuture()
.get();


// 获取最终解析消息, 也就是 decode flow 导出的数据
final ByteIterator it = outputFrame.iterator();
int length = it.getInt(ByteOrder.BIG_ENDIAN); // 出站自动加的长度, 也就是被 BidiFlow 自动打包 [int32:长度][byte[]:二进制内容]
String message = it.toByteString().utf8String();
logger.infof("result: length = %d, message = %s", length, message);

// 关闭系统
actorConfig.stop(system);
}
}

这里的 Flow 概念就是对于数据流最晦涩难懂的部分, 核心问题如下

  • BidiFlow<?>: 双端数据流处理

  • Flow<?>: 单向数据流处理方式

  • BidiFlow.reversed(): 数据处理的反转处理 (注意区分数组列表的 reversed 概念, 这里是双端处理的反转)

  • Sink.*: 消息遍历转化的机制处理

注意: simpleFramingProtocol 的 int32 长度字段是不包含自己的长度单位

BidiFlow 内部有两条独立、方向相反的单向通道, 四个对外端口分别是:

1
2
3
4
5
6
7
        原 BidiFlow
I1 ────────────────► O1
┌───────────────────────────┐
│ 通道1: 编码/出站处理逻辑 │
│ 通道2: 解码/入站处理逻辑 │
└───────────────────────────┘
O2 ◄─────────────── I2

调用 reversed() 会生成一个新的 BidiFlow, 四个对外端口和原模块做了一次交换映射:

新 BidiFlow 端口 对应原 BidiFlow 端口
新 I1 原 O2
新 O1 原 I2
新 I2 原 O1
新 O2 原 I1

交换完成之后的通道逻辑就变了

1
2
3
4
5
6
7
        新 BidiFlow
I1 ────────────────► O1
┌───────────────────────────┐
│ 通道1: 解码/入站处理逻辑 │
│ 通道2: 编码/出站处理逻辑 │
└───────────────────────────┘
O2 ◄─────────────── I2

简单来说, 就是不调用 reversed 的时候, 客户端原生数据后置 simpleFramingProtocol 处理并优先给你使用 (最后调用Framing);
而调用 reversed 之后就会反转过来, 先执行 simpleFramingProtocol 处理完数据再转发剔除长度 int32 字段的二进制内容

网络服务

Pekko 本身就内容网络模块, 可以直接采用内置 TCP 服务初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* 网络交换 - 怎么去设计网关
*/
@QuarkusTest
public class TcpBehaviorTest {
// 其他略

/**
* TCP-Echo 服务器
*/
@Test
void echo() throws Exception {
// 构建 Actor 系统
ActorSystem<Void> system = actorConfig.build((ActorContext<Void> ignore) -> {

}, this.actorConfig.load());


// 主要该测试是用于巩固之前的 pekko-stream 概念
final int maximumMessageLength = 1 << 20; // 最大的 1M 数据量
final BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> bidiFlow =
Framing.simpleFramingProtocol(maximumMessageLength);


// 构建 TCP 服务端, 找到 Pekko 流模型就是构建 Source 端点
final int port = 9999;
final int backlog = 1024;
final boolean halfClose = false;
final Duration idleTimeout = Duration.ofSeconds(60);
final Tcp instance = Tcp.get(system);
final Source<Tcp.IncomingConnection, CompletionStage<Tcp.ServerBinding>> source = instance.bind(
"127.0.0.1", port, backlog, Collections.emptyList(), halfClose, Optional.of(idleTimeout));


// 每个 TCP 客户端都会自动构建成新的 Sink 返回
// 注意: 当设置 .run(system) 的时候, 就代表让 ActorSystem 启动服务
CompletionStage<Tcp.ServerBinding> stage = source.to(Sink.foreach(connection -> {

// 注意: // 每个会话独立构建业务流, BidiFlow 全局共享
Flow<ByteString, ByteString, NotUsed> inputFlow = Flow.of(ByteString.class).map(payload -> {
// 这里不需要处理多余的功能, 只需要将数据返回和打印日志数据
// 正式上线调整成 debug 打印
logger.infof("input bytes = %s", Arrays.toString(payload.toArray()));
return payload;
});

// 核心概念: 反转输入处理
inputFlow = bidiFlow.reversed().join(inputFlow);


// 客户端会话插入自定义 Flow 处理
connection.handleWith(inputFlow, system);

})).run(system);

// 验证服务器启动的状态
stage.whenComplete(((serverBinding, throwable) -> {
if (throwable != null) {
logger.info("tcp startup failed", throwable);
return;
}

// 启动成功打印
logger.infof("tcp startup succeed = %s", serverBinding.localAddress());

// 这里模拟客户启动完成之后发送数据
final int id = 10001;
final byte[] bytes = "Hello.World".getBytes(StandardCharsets.UTF_8);

// 计算长度
int payloadLength = Integer.BYTES + bytes.length; // (sizeof(int32) = 4) + length: 协议ID长度 + 消息内容长度
int totalFrameLength = Integer.BYTES + payloadLength; // 总帧长 = 长度字段 + 用户负载

// 构建消息帧
ByteBuffer buffer = ByteBuffer.allocate(totalFrameLength);
buffer.putInt(payloadLength); // 写入总长
buffer.putInt(id); // 写入协议ID
buffer.put(bytes); // 写入消息内容
byte[] frame = buffer.array(); // 获取消息二进制
logger.infof("send frame = %s", Arrays.toString(frame));


// Socket 发送并接收
try (Socket socket = new Socket("127.0.0.1", port);
DataInputStream dis = new DataInputStream(socket.getInputStream());
OutputStream outbound = socket.getOutputStream()) {

// 发送数据帧
outbound.write(frame);
outbound.flush();

// 读取响应: 先读4字节长度, 确保读满4字节长度
byte[] lengthBuf = new byte[Integer.BYTES];
dis.readFully(lengthBuf);
int respLength = ByteBuffer.wrap(lengthBuf).getInt();

// 读满完整负载
byte[] respPayload = new byte[respLength];
dis.readFully(respPayload);

// 解析响应
ByteBuffer respBuf = ByteBuffer.wrap(respPayload);
int respProtocolId = respBuf.getInt();
byte[] respBody = new byte[respLength - Integer.BYTES];
respBuf.get(respBody);
String respMessage = new String(respBody, StandardCharsets.UTF_8);

logger.infof("Response Id: %d", respProtocolId);
logger.infof("Response Body: %s", respMessage);

} catch (IOException e) {
logger.error(e.getMessage());
}
}));


// 延迟1s之后关闭服务
Thread.sleep(Duration.ofSeconds(1));
actorConfig.stop(system);
}
}

tcp-echo 服务特别简单, 主要考验的是之前的 Flow 处理和非共享性 (每个会话连接 Flow 是独享的)

不过需要注意的是目前 echo 示例只能作为单进程的消息回显, 没办法结合 Actor 系统去管理接受请求和响应数据

1
map(payload -> return payload) 是纯无状态函数, 只能做数据转换而无法持有会话状态去做复杂业务处理

所以接下来就是要单独为所有会话连接构建 Actor 来处理这部分的功能, 从而设计出真正高可用网关服务

高级服务

这里就需要用到高级的数据流功能

  • ActorSource.actorRef: 强类型专属的 Source Actor 功能

  • ActorSink.actorRef: 强类型专属的 Sink Actor 功能

依靠这些 API 就能实现构建 Actor 动态会话, 这里先编写个简单的网关功能, 后面再慢慢解释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/**
* 网络交换 - 怎么去设计网关
*/
@QuarkusTest
public class TcpBehaviorTest {
/**
* 高级应用: 内部只编写数据输入与输出, 并没有处理异常和主动/被动断开的任何逻辑
*/
@Test
void advanced() throws Exception {

// 构建 Actor 系统
ActorSystem<Void> system = actorConfig.build((ActorContext<Void> ignore) -> {

}, this.actorConfig.load());


// 主要该测试是用于巩固之前的 pekko-stream 概念
final int maximumMessageLength = 1 << 20; // 最大的 1M 数据量
final BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> bidiFlow =
Framing.simpleFramingProtocol(maximumMessageLength);


// 构建 TCP 服务端, 找到 Pekko 流模型就是构建 Source 端点
final int port = 9999;
final int backlog = 1024;
final boolean halfClose = false;
final Duration idleTimeout = Duration.ofSeconds(60);
final Tcp instance = Tcp.get(system);
final Source<Tcp.IncomingConnection, CompletionStage<Tcp.ServerBinding>> source = instance.bind(
"127.0.0.1", port, backlog, Collections.emptyList(), halfClose, Optional.of(idleTimeout));


// 每个 TCP 客户端都会自动构建成新的 Sink 返回
// 注意: 当设置 .run(system) 的时候, 就代表让 ActorSystem 启动服务
CompletionStage<Tcp.ServerBinding> stage = source.to(Sink.foreach(connection -> {


// 构建出站 Source: Actor 往流里发响应
Source<ByteString, ActorRef<ByteString>> outboundSource = ActorSource.actorRef(
(obj) -> {
// completionMatcher: 匹配到特定消息时, 触发流正常关闭, 以 boolean 返回判断是否要关闭
return false;
},
(obj) -> {
// 流异常的信号
return Optional.empty();
},
1024, // 缓冲区大小
OverflowStrategy.fail() // 设置数据移除之后的处理方法: fail() = 直接弹出失败错误
);

// 先实例化出站 Source 拿到响应 ActorRef
Pair<ActorRef<ByteString>, Source<ByteString, NotUsed>> outboundPair = outboundSource.preMaterialize(system);
ActorRef<ByteString> outboundRef = outboundPair.first();
Source<ByteString, NotUsed> outboundStream = outboundPair.second();

// 会话连接的时候构建动态 Actor, 这里可以把 outboundActor 对象传入自定义 Actor
final String name = UUID.randomUUID().toString();
final ActorRef<ByteString> owner = system.systemActorOf(Behaviors.setup((ctx) -> {
// 这里就是 Actor 获取到发送器, 后续内部自行处理业务推送
final org.slf4j.Logger log = ctx.getLog();
log.info("session created, uuid = {}, outbound = {}", name, outboundRef.path());

// 构建简单的响应功能
return Behaviors.receiveMessage(msg -> {
log.info("session receive message, bytes = {}", Arrays.toString(msg.toArray()));
return Behaviors.same();
});
}), name, Props.empty());


// 入站 Sink: 流把消息发给会话 Actor
Sink<ByteString, NotUsed> inboundSink = ActorSink.actorRef(
owner, // 带类型的 actorRef 转化为无类型
ByteString.fromString("__COMPLETE__"), // 流正常完成时发送的消息, 这里随便发个数据
(throwable) -> {
// 流异常的信号, 这里先随便传递个异常
return ByteString.fromString("__ERROR__:" + throwable.getMessage());
}
);

// 拼接成完整的业务双向 Flow
Flow<ByteString, ByteString, NotUsed> flow = Flow.fromSinkAndSource(inboundSink, outboundStream);

// ========== 分帧层 + 业务层 = 完整 TCP 处理器 ==========
Flow<ByteString, ByteString, NotUsed> handler =
bidiFlow.reversed().join(flow);
connection.handleWith(handler, system);
})).run(system);


// 验证服务器启动的状态
stage.whenComplete(((serverBinding, throwable) -> {
if (throwable != null) {
logger.info("tcp startup failed", throwable);
return;
}

// 启动成功打印
logger.infof("tcp startup succeed = %s", serverBinding.localAddress());

// 这里模拟客户启动完成之后发送数据
final int id = 10001;
final byte[] bytes = "Hello.World".getBytes(StandardCharsets.UTF_8);

// 计算长度
int payloadLength = Integer.BYTES + bytes.length; // (sizeof(int32) = 4) + length: 协议ID长度 + 消息内容长度
int totalFrameLength = Integer.BYTES + payloadLength; // 总帧长 = 长度字段 + 用户负载

// 构建消息帧
ByteBuffer buffer = ByteBuffer.allocate(totalFrameLength);
buffer.putInt(payloadLength); // 写入总长
buffer.putInt(id); // 写入协议ID
buffer.put(bytes); // 写入消息内容
byte[] frame = buffer.array(); // 获取消息二进制
logger.infof("send frame = %s", Arrays.toString(frame));


// Socket 发送并接收
try (Socket socket = new Socket("127.0.0.1", port);
DataInputStream dis = new DataInputStream(socket.getInputStream());
OutputStream outbound = socket.getOutputStream()) {

// 发送数据帧
outbound.write(frame);
outbound.flush();

// 读取响应: 先读4字节长度, 确保读满4字节长度
byte[] lengthBuf = new byte[Integer.BYTES];
dis.readFully(lengthBuf);
int respLength = ByteBuffer.wrap(lengthBuf).getInt();

// 读满完整负载
byte[] respPayload = new byte[respLength];
dis.readFully(respPayload);

// 解析响应
ByteBuffer respBuf = ByteBuffer.wrap(respPayload);
int respProtocolId = respBuf.getInt();
byte[] respBody = new byte[respLength - Integer.BYTES];
respBuf.get(respBody);
String respMessage = new String(respBody, StandardCharsets.UTF_8);

logger.infof("Response Id: %d", respProtocolId);
logger.infof("Response Body: %s", respMessage);

} catch (IOException e) {
logger.error(e.getMessage());
}
}));

// 延迟1s之后关闭服务
Thread.sleep(Duration.ofSeconds(1));
actorConfig.stop(system);
}

}

内部的核心要点就在 source.to() 动态会话连接, 这里的流程是这样的

步骤 代码对应位置 作用
1 ActorSource.actorRef(...) 构建出站方向的流源,物化后生成一个 ActorRef<ByteString>,业务 Actor 向它发消息就等于写入流
2 outboundSource.preMaterialize(...) 提前物化出站流,拿到发送端 Actor 引用,交给业务会话 Actor 持有
3 system.systemActorOf(...) 为每个连接创建独立的会话 Actor,独享状态、独享邮箱,接管出站发送能力
4 ActorSink.actorRef(...) 构建入站方向的流汇,流里的数据会自动发送给会话 Actor
5 Flow.fromSinkAndSource(in, out) 入站 Sink + 出站 Source 拼接成完整的双向业务流,上下层都是 ByteString 类型
6 bidiFlow.reversed().join(flow) 分帧层反转后和业务流闭环,外层对接网络字节流,内层对接纯业务负载
7 connection.handleWith(handler, system) 把完整处理器和 TCP 物理连接绑定,数据开始流转

虽然看起来已经顺利运行, 但是内部其实还有很多优化的点, 需要将相关功能做成通用处理, 常规正常消息会话有以下消息类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* 通用事件接口, 用于内部派生处理
*/
interface IEvent extends Serializable {
}


/**
* TCP 会话连接完成通知
*/
record Connected(
String uuid,
Tcp.IncomingConnection incoming,
ActorRef<ByteString> outbound
) implements IEvent {

}

/**
* 流输入数据 - 内部消化信号, 用于 Flow 流处理消息之后返回数据
*/
record Inbound(
ByteString bytes
) implements IEvent {

}

/**
* 流输入数据 - 外部通知信号, 用于外部通知 Actor 发送数据
*/
record Outbound(
ByteString bytes
) implements IEvent {

}


/**
* 连接关闭信息 - 主动关闭
*/
record Closed(
String uuid,
int reason // 退出状态, 默认 0 代表常规关闭
) implements IEvent {

}

/**
* TCP 会话异常通知
*/
record Except(
Throwable throwable
) implements IEvent {

}