后端微服务【免费下载链接】akka.netCanonical actor model implementation for .NET with local distributed actors in C# and F#.项目地址https://gitcode.com/gh_mirrors/ak/akka.net点击查看免费下载本文基于 Akka.NET 官方文档 Console Application 展开完整演示如何用 .NET 控制台宿主搭建一个最小的 Akka.NET 应用定义消息类型Greet、实现ReceiveActor派生 Actor、启动ActorSystem并发送首条消息。读完本篇你将掌握控制台场景下 Actor 的创建、消息投递、生命周期回调PreStart/PostStop以及系统优雅终止的标准写法并能对照仓库源码理解每个 API 背后的实现。一、控制台场景的定位在 部署场景总览 中Akka.NET 将Console Application列为最基础的部署形态控制台应用能让你以最直接的方式观察软件的入口与退出点快速验证一个新的 actor 应用是否按预期启动、处理消息并退出。仓库中对应的可运行示例位于 src/examples/HelloAkka是一个独立的Exe工程仅依赖核心库 src/core/Akka/Akka.csprojProject SdkMicrosoft.NET.Sdk PropertyGroup OutputTypeExe/OutputType TargetFramework$(NetTestVersion)/TargetFramework ImplicitUsingsenable/ImplicitUsings Nullableenable/Nullable IsPackablefalse/IsPackable /PropertyGroup ItemGroup ProjectReference Include..\..\..\core\Akka\Akka.csproj / /ItemGroup /Project从项目结构看Program.cs使用了顶层语句与ImplicitUsings因此无需显式using System.Threading.Tasks即可使用Task.Delay。在仓库中构建并运行该工程的方式为dotnet run --project src/examples/HelloAkka/HelloWorld/HelloWorld.csproj下面按文档的三大步骤逐一讲解消息类 → Actor 类 → 控制台宿主。二、创建消息类Greet向 actor 下达指令的方式就是给它发送消息Greet就是本例中被发送的消息类型源码src/examples/HelloAkka/HelloWorld/Greet.csnamespace HelloWorld { /// summary /// Immutable message type that actor will respond to /// /summary public class Greet { public string Who { get; private set; } public Greet(string who) { Who who; } } }两个值得注意的设计点不可变消息Who属性只有private set消息一旦被构造就不可修改。actor 消息会在actor 间、甚至未来经 Akka.Remote 跨进程传递不可变类型天然避免了多线程环境下的共享状态问题这也是仓库示例刻意强调Immutable message type的原因。类型安全ReceiveActor的ReceiveT按类型分发消息Greet作为独立类型可以精确匹配处理器避免字符串协议式的脆弱约定。三、创建GreetingActorActor 是ReceiveActor的派生类负责响应Greet消息源码src/examples/HelloAkka/HelloWorld/GreetingActor.csusing Akka.Actor; namespace HelloWorld { /// summary /// The actor class /// /summary public class GreetingActor : ReceiveActor { public GreetingActor() { // Tell the actor to respond to the Greet message ReceiveGreet(greet Console.WriteLine($Hello {greet.Who})); } protected override void PreStart() { Console.ForegroundColor ConsoleColor.Green; Console.WriteLine(Good Morning, we are awake!); } protected override void PostStop() { Console.ForegroundColor ConsoleColor.Red; Console.WriteLine(Good Night, going to bed!); } } }生命周期回调PreStart/PostStopPreStart会在 Akka 框架启动该 actor 时被调用PostStop则在 actor 停止之后被调用——本例用绿色打印醒来、红色打印睡觉来可视化这两个时刻。它们是ActorBase生命周期钩子的一部分适合放置初始化资源、订阅/取消订阅、日志等不需要处理消息的逻辑。ReceiveT的底层机制ReceiveActor的源码在 src/core/Akka/Actor/ReceiveActor.cs。从源码结构看其工作机制是ReceiveT只能在 actor 构造函数或Become期间注册处理器否则抛出InvalidOperationException构造函数调用会先压入一个 handler 栈每条入站消息经由sealed的OnReceive(object message)分发给当前 handler 集合ReceiveGreet注册的处理器只匹配Greet类型若没有任何处理器匹配消息会走Unhandled(message)由DeadLetterActorRef等机制兜底除ReceiveT外源码还提供ReceiveAny、带谓词的ReceiveT(PredicateT, ActionT)以及会挂起 actor 直至任务完成的ReceiveAsyncT配合Become/BecomeStacked可以实现行为切换有限状态风格的状态机写法。本例中ReceiveGreet(greet Console.WriteLine($Hello {greet.Who}))即注册了一个同步处理器收到Greet时打印问候语并返回已处理。四、创建控制台宿主Program.cs整个宿主入口只有寥寥数行源码src/examples/HelloAkka/HelloWorld/Program.csusing Akka.Actor; using HelloWorld; // ReSharper disable SuggestVarOrType_SimpleTypes ActorSystem system ActorSystem.Create(the-universe); // create actor and get a reference to it. // this will be an ActorRef, which is not a // reference to the actual actor instance // but rather a client or proxy to it IActorRef greeter system.ActorOfGreetingActor(greeter); // send a message to the actor greeter.Tell(new Greet(World)); // give the actor a moment to process the message // (it should process it in under a micro-second, but it happens asynchronously) await Task.Delay(TimeSpan.FromSeconds(1)); system.Stop(greeter); await system.Terminate();逐段拆解步骤代码说明1ActorSystem.Create(the-universe)创建并立即启动名为the-universe的 actor 系统2system.ActorOfGreetingActor(greeter)创建 actor 并拿到IActorRef——注意它是客户端/代理而非 actor 实例本身3greeter.Tell(new Greet(World))异步投递一条Greet消息4await Task.Delay(1s)给 actor 留出异步处理消息的时间5system.Stop(greeter)向 actor 发起停止请求触发PostStop6await system.Terminate()终止整个 actor 系统进程随之退出五、源码印证每个 API 到底做了什么5.1ActorSystem.Create的四个重载ActorSystem 中Create提供了多个重载ActorSystem.cs#L261-L308public static ActorSystem Create(string name, Config config) // 名称 HOCON 配置 public static ActorSystem Create(string name, BootstrapSetup setup) // 名称 程序化 Bootstrap 配置 public static ActorSystem Create(string name, ActorSystemSetup setup) // 名称 完整 Setup public static ActorSystem Create(string name) // 仅名称本例使用文档示例使用的单参数Create(name)会回退到ConfigurationFactory.Default()加载默认配置reference.conf等因此控制台应用零配置即可运行。源码注释还明确要求系统名必须是 URI 友好的只能包含[a-zA-Z0-9]及非前导的-例如the-universe合法而包含.或空格的名字非法。所有重载最终都汇入私有方法CreateAndStartSystem先new ActorSystemImpl(...)再system.Start()——也就是说Create返回时系统已经处于运行状态。5.2ActorOfT是扩展方法system.ActorOfGreetingActor(greeter)实际调用的是 ActorRefFactoryExtensions 中的扩展方法ActorRefFactoryExtensions.cs#L24-L28public static IActorRef ActorOf[DynamicallyAccessedMembers(Props.ActorTypeMembers)] TActor( this IActorRefFactory factory, string name null) where TActor : ActorBase, new() { return factory.ActorOf(Props.CreateTActor(), name: name); }两个关键约束可以从签名中直接读出TActor : ActorBase, new()—— actor 类型必须有公共无参构造函数这也是为什么GreetingActor没有定义带参构造函数若需注入参数应改用Props.Create(() new MyActor(dep))或 DI 方案底层通过Props.CreateTActor()构造描述符再创建 actor因此每次ActorOf都会生成一个新的 actor 实例及其邮箱。返回的IActorRef是逻辑引用代理Tell只是把消息入队并不直接触碰 actor 内部状态——这正是文档注释里not a reference to the actual actor instance, but rather a client or proxy to it的含义。5.3Tell的异步语义与Terminate消息投递走IActorRef.Tell见 ActorRef.cs#L337 及其扩展方法。投递是异步的Tell返回时消息可能尚未被处理所以示例才需要Task.Delay兜底等待。生产代码中更推荐用Ask模式或system.WhenTerminated等结构化同步手段而非固定延时。系统侧Terminate的语义在 ActorSystem.cs#L384-L406 有明确注释终止 guardian actor进而递归停止其子树中的所有 actor本例中greeter作为 guardian 的子节点会先收到停止PostStop在Terminate完成前执行最后关闭系统并返回可等待的TaskWhenTerminated属性则暴露同样的终止信号。ActorSystem实现了IDisposableDispose时若系统尚未终止会同步Terminate().Wait()。六、预期运行输出按上述步骤运行示例控制台将依次出现Good Morning, we are awake! ← PreStart绿色 Hello World ← Greet 处理器 Good Night, going to bed! ← PostStop红色这三行分别对应 actor 的启动 → 处理消息 → 停止完整生命周期恰好验证了文档中PreStart/PostStop的说明。七、小结与延伸本篇覆盖了 console.md 文档的三大步骤并借助仓库源码补齐了实现细节消息不可变 C# 类Greet.csActorReceiveActor 类型化ReceiveT处理器 PreStart/PostStop钩子GreetingActor.cs、ReceiveActor.cs宿主ActorSystem.Create→ActorOfT→Tell→Stop→await Terminate()Program.cs、ActorSystem.cs。掌握这个最小闭环后可以继续沿着 部署场景 演进ASP.NET Core 宿主 中用 actor 承载重型业务逻辑、Headless Service 后台常驻运行、以及 Native AOT 与裁剪 场景下的注意事项更深入的 actor API 可参考 Receive Actor API 与 非类型化 Actor API。赞分享后端微服务【免费下载链接】akka.netCanonical actor model implementation for .NET with local distributed actors in C# and F#.项目地址https://gitcode.com/gh_mirrors/ak/akka.net点击查看免费下载相关推荐使用 AWS SDK for Ruby 实战 AWS Lambda从 Hello World 到完整函数生命周期管理使用 AWS SDK for Ruby 实战 AWS Lambda从 Hello World 到完整函数生命周期管理 导读 本文以 ruby/example_示例工程教程后端Brave 浏览器内置了什么隐私防护4 个机制一次讲明白Brave 浏览器内置了什么隐私防护4 个机制一次讲明白 Brave 浏览器是一款基于 Chromium 的隐私保护浏览器解决的核心问题是你什么都不用装使用 AWS SDK for Rust 操作 Amazon EC2从 Hello World 到完整实例生命周期管理使用 AWS SDK for Rust 操作 Amazon EC2从 Hello World 到完整实例生命周期管理 本文基于 AWS Code Exampl示例工程教程后端创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考