gpt4 book ai didi

scala - 将依赖项注入(inject)集群持久 Akka Actor 的正确方法?

转载 作者:行者123 更新时间:2023-12-03 17:48:17 25 4
gpt4 key购买 nike

我正在使用 Akka PersistenceCluster Sharding .向此类 PersistentActor 提供依赖关系的正确方法是什么? -s?

据我了解,将它们作为构造函数参数传递是不可能的,因为集群分片正在创建这些参与者。

使用 Spring/Guice/等。不是惯用的Scala(并且可能还有其他问题(?))。

使用 object实现单例会导致繁琐的测试并且看起来很糟糕。

什么是正确的方法?

附言如果您打算建议 Cake 模式,请在这个特定的 Akka Persistence Cluster Sharding 上下文中提供示例代码。

最佳答案

更新后的版本:
我之前提供的解决方案不允许在单元测试用例中模拟被测参与者的服务。

我正在使用该文章中提供的一种解决方案 http://letitcrash.com/post/55958814293/akka-dependency-injection这就是所谓的“方面编织”,它包括使用面向方面的编程将依赖项注入(inject)到参与者中。
此解决方案可用于在不受 Spring 容器控制的任何 bean 上注入(inject) Spring 依赖项(可能对遗留代码有用)。

上面的文章提供了一个完整的例子:https://github.com/huntc/akka-spring/blob/f137c98b621517301f636e6ea03519388fcd5fff/src/main/scala/org/typesafe/Akkaspring.scala

要在基于 Spring 的应用程序中启用方面编织,您应该查看 Spring doc 上的文档
就我而言,在码头应用程序服务器上,它包括使用 spring 代理并将其设置在 jvm 参数中。

就测试而言,我:

  • 为注入(inject)的服务创建了 setter
  • 为我的 Actor 创建​​了基本配置,为我的依赖项引用了空 bean
  • 在我的测试用例中实例化了 Actor
  • 用模拟替换 Actor 的服务
  • 运行 actor 的内部方法并检查结果、actor 的状态或对依赖项的调用

  • 原来的:

    I am using Akka in a Spring Application to enable clustering. At first it raises the following issue: you cannot inject spring managed dependencies in the actor constructor, as you said. (it tries to serialize the application context and fails)

    So I created a class that holds the application context and provides a static method to retrieve beans I need. I retrieve the bean only if I need it, this way:

    public void onReceive{
    if (message instanceof HandledMessage) {
    (MyService) SpringApplicationContext.getBean("myService");
    ...
    }
    }

    It's not conventional but it does the job, what do you think? Hope otherwise it might help another one.

    关于scala - 将依赖项注入(inject)集群持久 Akka Actor 的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28211285/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com