js实现actor模型
Actor模型简介
Actor模型是一种并发计算模型,将每个“Actor”视为独立的计算单元,通过消息传递进行通信。每个Actor拥有私有状态,避免共享内存带来的竞争问题,适合分布式和高并发场景。
实现Actor模型的核心要素
1. 消息队列
每个Actor维护一个消息队列,异步接收和处理消息。
2. 隔离状态
Actor内部状态不能被外部直接修改,只能通过消息触发变更。

3. 消息传递
Actor之间通过发送不可变消息通信,消息发送是非阻塞的。
JavaScript实现示例
基础Actor类
class Actor {
constructor() {
this.queue = [];
this.isProcessing = false;
}
// 异步处理消息
async processQueue() {
if (this.isProcessing || this.queue.length === 0) return;
this.isProcessing = true;
const message = this.queue.shift();
try {
await this.onMessage(message);
} catch (error) {
console.error("Actor处理消息失败:", error);
}
this.isProcessing = false;
this.processQueue(); // 处理下一条
}
// 发送消息到Actor
send(message) {
this.queue.push(message);
this.processQueue();
}
// 子类需实现的具体逻辑
onMessage(message) {
throw new Error("需实现onMessage方法");
}
}
使用示例
class CounterActor extends Actor {
constructor() {
super();
this.count = 0;
}
async onMessage(message) {
if (message.type === "increment") {
this.count++;
console.log("当前计数:", this.count);
} else if (message.type === "decrement") {
this.count--;
console.log("当前计数:", this.count);
}
}
}
// 创建Actor并发送消息
const counter = new CounterActor();
counter.send({ type: "increment" }); // 输出: 当前计数: 1
counter.send({ type: "increment" }); // 输出: 当前计数: 2
counter.send({ type: "decrement" }); // 输出: 当前计数: 1
进阶优化方向
1. 支持跨线程通信
使用Web Worker实现多线程Actor,通过postMessage传递消息。

2. 超时与错误处理
为消息处理添加超时机制和重试逻辑,提升健壮性。
3. 路由与集群
扩展为Actor集群,通过路由策略(如一致性哈希)分配消息。
4. 使用现有库
- Akka.js: 移植自JVM的Actor模型框架。
- XState: 基于状态机的Actor实现。
注意事项
- 避免在消息中传递可变对象,防止意外共享状态。
- 对于高性能场景,考虑批量处理消息(如每10ms处理一次队列)。
- 在Node.js中可使用
cluster模块实现多进程Actor。






