问题描述
Petabridge博客的Akka.Persistence简介清楚地表明您不能有多个具有相同PersistenceId的角色:
The Petabridge blog's Akka.Persistence intro makes it clear that you can't have multiple actors with the same PersistenceId:
[...]因此,请设想一下,如果您有两个具有相同PersistenceId的actor,但写入同一存储区的序列号不同.这将是混乱的,并且不可避免地会出错-因此,至关重要的是,每个PersistenceId在您的ActorSystem中都是全局唯一的(至少对于写入该商店的所有Actor而言都是如此).
[...] so imagine if you have two actors with the same PersistenceId but different sequence numbers writing to the same store. It will be chaos and will inevitably error out - so that’s why it’s crucial that every PersistenceId be globally unique within your ActorSystem (at least for all actors writing to that store.)
我可以想到一种情况,您将有两个单独的参与者:一个负责将持久性状态保存到数据库中(例如,调用Persist()
),另一个则是在手动请求时从日记中重播消息(即调用Recover()
).读写操作可能来自不同的参与者.只有一个人写过,只有一个人读过.但是,两者都需要相同的PersistenceId.
I can think of a scenario where you would have two separate actors: one that takes care of saving persistence state to database (i.e. calls Persist()
), and another one that replays messages from the journal when manually requested to do so (i.e. calls Recover()
). The read and write operations would occur from different actors. Only one ever writes, and only one ever reads. However, both need the same PersistenceId.
我相信在这种情况下,让两个参与者使用相同的PersistenceId应该是安全的.但是,鉴于以上引述的上述警告,在实践中这种方法可能会很危险吗?
I believe that in this scenario it should be safe to have two actors using the same PersistenceId. But given the above warnings quoted above, is there any reason why such an approach could be dangerous in practice?
推荐答案
The behaviour you require is already exposed as Persistent Actors and Persistent Views. From the docs:
已更新,以提供有关如何在持久视图"中访问事件的更多信息.
updated to provide more info on how to access events in the Persistent View.
您可以通过覆盖Persistent View
的Receive
方法从日记中加载.此方法的参数是一个对象,因此您需要将该对象强制转换为通过Persistent Actor
持续存在的任何事件.
You can load from a journal by overriding the Receive
method of a Persistent View
. The argument for this method is an object, so you'll need to cast that object to whatever event(s) you have persisted via the Persistent Actor
.
Receive
方法还处理您传递给视图的任何其他消息-例如来自表示层的读取请求.我通常将事件列表内部存储在View中,并从中返回自定义视图模型.
The Receive
method also handles any other messages you pass to the View - e.g. a read request from the presentation layer. I usually store a list of events internally in the View and return a custom view model from these.
protected override bool Receive(object message)
{
// if the message is a previously persisted event, update our internal list
var e = message as MyEvent;
if (e != null) _events.Add(e);
return true;
// if the message is a request for a view model, read from our list of stored events
var r = message as ReadRequest;
if (r == null) return false;
Sender.Tell(new ViewModel(_events));
return true;
}
这篇关于我可以从具有相同PersistenceId的不同角色读取/写入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!