js实现actor模型
Actor 模型简介
Actor 模型是一种并发计算模型,通过独立实体(Actor)之间的消息传递实现并行处理。每个 Actor 拥有私有状态,通过异步消息与其他 Actor 通信,避免共享内存和锁机制。
JavaScript 实现 Actor 模型的核心要素
创建 Actor 类
class Actor {
constructor() {
this.mailbox = [];
this.isProcessing = false;
}
send(message) {
this.mailbox.push(message);
this.process();
}
async process() {
if (this.isProcessing) return;
this.isProcessing = true;
while (this.mailbox.length > 0) {
const message = this.mailbox.shift();
await this.receive(message);
}
this.isProcessing = false;
}
receive(message) {
throw new Error("Must implement receive method");
}
}
实现具体 Actor
class CounterActor extends Actor {
constructor() {
super();
this.count = 0;
}
receive(message) {
switch (message.type) {
case 'INCREMENT':
this.count++;
break;
case 'DECREMENT':
this.count--;
break;
case 'GET':
message.reply(this.count);
break;
}
}
}
消息传递机制
const counter = new CounterActor();
// 发送消息
counter.send({ type: 'INCREMENT' });
counter.send({ type: 'INCREMENT' });
// 带回复的消息
const replyPromise = new Promise(resolve => {
counter.send({
type: 'GET',
reply: resolve
});
});
replyPromise.then(count => {
console.log(`Current count: ${count}`);
});
进阶优化方案
批量处理消息 通过设置阈值或时间窗口批量处理消息,减少上下文切换:
class BatchActor extends Actor {
constructor(batchSize = 10) {
super();
this.batchSize = batchSize;
}
async process() {
if (this.isProcessing) return;
this.isProcessing = true;
while (this.mailbox.length > 0) {
const batch = this.mailbox.splice(0, this.batchSize);
await this.receiveBatch(batch);
}
this.isProcessing = false;
}
receiveBatch(messages) {
// 实现批量处理逻辑
}
}
错误处理机制 为 Actor 添加错误边界保护:

class SafeActor extends Actor {
async process() {
try {
await super.process();
} catch (error) {
this.handleError(error);
}
}
handleError(error) {
console.error('Actor error:', error);
}
}
现成库推荐
- Akka.js:TypeScript 实现的 Actor 模型库
- Nact:受 Erlang/Elixir 启发的轻量级实现
- XState:基于状态机的 Actor 模式实现
性能注意事项
- 避免在单个 Actor 中处理耗时操作
- 对于计算密集型任务考虑使用 Worker 线程
- 大型系统建议采用分形架构(Hierarchical Actors)






