传递上下文信息 [英] Passing Contextual Information

查看:29
本文介绍了传递上下文信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在将 akka.net 参与者添加到遗留系统的一部分.

We are in the process of adding akka.net actors to part of a legacy system.

基本思想是消息来自外部系统,它被传递给由 akka.net 参与者管理的逻辑,然后与执行诸如将数据保存到数据库之类的操作的遗留组件通信.

The basic idea is that a message comes in from an external system, it is handed off to a logic that is managed by akka.net actors which then talk to legacy components that do things like save data to the database.

遗留代码依赖于这样一个事实,即在 CallContext 中设置了 userId,然后它可以在执行数据库写入之前检索它(以存储诸如CreatedBy"和LastModifiedBy"之类的内容).很明显,一旦消息通过 actor 系统,CallContext 将不可用.

The legacy code relies on the fact that a userId is set in the CallContext, which it can then retrieve before doing database writes (to store things like "CreatedBy" and "LastModifiedBy"). It seems clear that the CallContext will not be available once the message is passed through the actor system.

这似乎是一个常见的问题/要求,但我一直无法通过谷歌或浏览 akka/akka.net 讨论组找到这个问题.

This seems like it would be a common problem/requirement, but I've been unable to find this question via google or looking through the akka/akka.net discussion groups.

akka.net 中是否有上下文包装器/信封的概念,或者是我将上下文信息的传递作为消息的显式部分的唯一选择?

Is there a concept of a contextual wrapper/envelope in akka.net, or is my only option to make the passing of contextual information an explicit part of the message?

推荐答案

由于您的消息可能会跨越 actor 系统边界传递,这里最好的选择似乎是包装要传递的 CallContext 和消息,并在消息到达时加载它到演员的领域之一.下面是使用 AroundReceive 方法的示例代码:

Since your message may be possibly passed across actor system boundaries, the best option here seems to be wrapping CallContext and message to be passed, and load it on message arrival to one of the actor's fields. Here is the example code using AroundReceive method:

public struct Wrapper {
    public readonly CallContext CallContext;
    public readonly object Message;
    ...
}

public abstract class ContextualActor : ReceiveActor {
    protected CallContext CallContext;
    protected override bool AroundReceive(Receive receive, object message) {
        if (message is Wrapper) {
            var wrapped = (Wrapper)message;
            CallContext = wrapped.CallContext;
            return base.AroundReceive(receive, wrapped.Message);
        }
        else return base.AroundReceive(receive, message);
    }

    public void Send(IActorRef aref, object message) => 
        aref.Tell(new Wrapper(CallContext, message))
}

这样,当消息到达actor的receive方法时,调用上下文就会被加载.请记住,为此,CallContext 必须是可序列化且不可变的,否则将不安全且无法正常工作.

This way, call context will be loaded already, when the message hits the receive method of an actor. Remember that for this, CallContext must be serializable and immutable, otherwise it won't be safe and work properly.

这篇关于传递上下文信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆