JavaPekkoPekko 网关设计
MeteorCat
需要 Stream 相关知识点: pekko-stream
简单来说就是如果涉及到大规模的消息交换, 最好实现 Source → Flow → Sink 的 inbound/outbound 双端队列
pekko 内部已经实现简单的数据交换分帧功能, 结合起来就可以构建自己的网关服务, 先简单引入必须要的依赖
1 2 3 4 5 6 7 8 9 10 11 12 13
| <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);
@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>:
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 { ActorSystem<Void> system = actorConfig.build((ActorContext<Void> ignore) -> {
}, this.actorConfig.load());
final int maximumMessageLength = 1 << 20; final BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> bidiFlow = Framing.simpleFramingProtocol(maximumMessageLength);
ByteString proto1001Message = ByteString .createBuilder() .putInt(1001, ByteOrder.BIG_ENDIAN) .append(ByteString.fromString("Hello.Protobuf-1001")) .result(); logger.infof("proto message 1001 = %s", Arrays.toString(proto1001Message.toArray()));
ByteString proto1001Frame = ByteString .createBuilder() .putInt(proto1001Message.size(), ByteOrder.BIG_ENDIAN) .append(proto1001Message) .result(); logger.infof("proto frame 1001 = %s", Arrays.toString(proto1001Frame.toArray()));
Flow<ByteString, ByteString, NotUsed> businessFlow = Flow.of(ByteString.class).map(payload -> { final ByteIterator it = payload.iterator(); int id = it.getInt(ByteOrder.BIG_ENDIAN); final ByteString body = it.toByteString(); logger.infof("decode message: id = %d, bytes = %s", id, Arrays.toString(body.toArray())); return body; });
Flow<ByteString, ByteString, NotUsed> businessHandler = bidiFlow.reversed().join(businessFlow);
ByteString outputFrame = Source.single(proto1001Frame) .via(businessHandler) .runWith(Sink.head(), system) .toCompletableFuture() .get();
final ByteIterator it = outputFrame.iterator(); int length = it.getInt(ByteOrder.BIG_ENDIAN); String message = it.toByteString().utf8String(); logger.infof("result: length = %d, message = %s", length, message);
actorConfig.stop(system); } }
|
这里的 Flow 概念就是对于数据流最晦涩难懂的部分, 核心问题如下
注意: 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 {
@Test void echo() throws Exception { ActorSystem<Void> system = actorConfig.build((ActorContext<Void> ignore) -> {
}, this.actorConfig.load());
final int maximumMessageLength = 1 << 20; final BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> bidiFlow = Framing.simpleFramingProtocol(maximumMessageLength);
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));
CompletionStage<Tcp.ServerBinding> stage = source.to(Sink.foreach(connection -> {
Flow<ByteString, ByteString, NotUsed> inputFlow = Flow.of(ByteString.class).map(payload -> { logger.infof("input bytes = %s", Arrays.toString(payload.toArray())); return payload; });
inputFlow = bidiFlow.reversed().join(inputFlow);
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; int totalFrameLength = Integer.BYTES + payloadLength;
ByteBuffer buffer = ByteBuffer.allocate(totalFrameLength); buffer.putInt(payloadLength); buffer.putInt(id); buffer.put(bytes); byte[] frame = buffer.array(); logger.infof("send frame = %s", Arrays.toString(frame));
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();
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()); } }));
Thread.sleep(Duration.ofSeconds(1)); actorConfig.stop(system); } }
|
tcp-echo 服务特别简单, 主要考验的是之前的 Flow 处理和非共享性 (每个会话连接 Flow 是独享的)
不过需要注意的是目前 echo 示例只能作为单进程的消息回显, 没办法结合 Actor 系统去管理接受请求和响应数据
1
| map(payload -> return payload) 是纯无状态函数, 只能做数据转换而无法持有会话状态去做复杂业务处理
|
所以接下来就是要单独为所有会话连接构建 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 {
ActorSystem<Void> system = actorConfig.build((ActorContext<Void> ignore) -> {
}, this.actorConfig.load());
final int maximumMessageLength = 1 << 20; final BidiFlow<ByteString, ByteString, ByteString, ByteString, NotUsed> bidiFlow = Framing.simpleFramingProtocol(maximumMessageLength);
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));
CompletionStage<Tcp.ServerBinding> stage = source.to(Sink.foreach(connection -> {
Source<ByteString, ActorRef<ByteString>> outboundSource = ActorSource.actorRef( (obj) -> { return false; }, (obj) -> { return Optional.empty(); }, 1024, OverflowStrategy.fail() );
Pair<ActorRef<ByteString>, Source<ByteString, NotUsed>> outboundPair = outboundSource.preMaterialize(system); ActorRef<ByteString> outboundRef = outboundPair.first(); Source<ByteString, NotUsed> outboundStream = outboundPair.second();
final String name = UUID.randomUUID().toString(); final ActorRef<ByteString> owner = system.systemActorOf(Behaviors.setup((ctx) -> { 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<ByteString, NotUsed> inboundSink = ActorSink.actorRef( owner, ByteString.fromString("__COMPLETE__"), (throwable) -> { return ByteString.fromString("__ERROR__:" + throwable.getMessage()); } );
Flow<ByteString, ByteString, NotUsed> flow = Flow.fromSinkAndSource(inboundSink, outboundStream);
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; int totalFrameLength = Integer.BYTES + payloadLength;
ByteBuffer buffer = ByteBuffer.allocate(totalFrameLength); buffer.putInt(payloadLength); buffer.putInt(id); buffer.put(bytes); byte[] frame = buffer.array(); logger.infof("send frame = %s", Arrays.toString(frame));
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();
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()); } }));
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 { }
record Connected( String uuid, Tcp.IncomingConnection incoming, ActorRef<ByteString> outbound ) implements IEvent {
}
record Inbound( ByteString bytes ) implements IEvent {
}
record Outbound( ByteString bytes ) implements IEvent {
}
record Closed( String uuid, int reason // 退出状态, 默认 0 代表常规关闭 ) implements IEvent {
}
record Except( Throwable throwable ) implements IEvent {
}
|