You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Akka 2.6.0+中如何通过Materializer传递supervision.decider

Akka 2.6.0+ 适配自定义监督策略到Materializer

在Akka 2.6.0及以上版本,ActorMaterializer被统一的Materializer接口替代,且不再支持通过Materializer实例直接配置全局监督策略。针对你的场景,下面提供两种可行的适配方案:

方案1:配置全局默认监督策略(通过ActorSystem)

Materializer本质绑定到ActorSystem,因此可以在创建ActorSystem时指定全局默认监督策略,所有基于该Materializer的操作都会继承这个策略。

代码示例:

import akka.actor.{ActorSystem, SupervisorStrategy}
import akka.stream.Materializer
import com.typesafe.config.ConfigFactory

// 自定义监督决策器
val customDecider: SupervisorStrategy.Decider = {
  case _: IllegalArgumentException => SupervisorStrategy.Restart
  case _: Exception => SupervisorStrategy.Resume
}

// 方式1:通过配置字符串配置策略类
val systemWithConfig = ActorSystem("MySystem", ConfigFactory.parseString("""
  akka.actor.default-supervision-strategy = "com.example.MyCustomSupervisionStrategy"
""").withFallback(ConfigFactory.load()))

// 方式2:程序化配置(动态指定策略)
class CustomSupervisionStrategy extends SupervisorStrategy.DefaultStrategy(customDecider)
val system = ActorSystem("MySystem")
system.settings.config = system.settings.config.withValue(
  "akka.actor.default-supervision-strategy",
  ConfigFactory.fromAnyRef(classOf[CustomSupervisionStrategy].getName).root()
)

// 获取绑定到该ActorSystem的Materializer
val mat: Materializer = Materializer(system)

方案2:针对特定操作传递监督策略(通过ActorAttributes)

如果你不需要全局生效,仅针对某部分操作使用自定义策略,可以通过ActorAttributes在具体组件(比如Actor)创建时传递监督策略,覆盖全局设置。

代码示例:

import akka.actor.{Actor, ActorAttributes, Props, SupervisorStrategy}
import akka.stream.Materializer

val system = ActorSystem("MySystem")
val mat: Materializer = Materializer(system)

// 自定义监督决策器
val customDecider = SupervisorStrategy.stoppingDecider

// 创建Actor时通过属性传递自定义策略
val myActor = mat.system.actorOf(
  Props[MyBusinessActor].withAttributes(ActorAttributes.supervisionStrategy(customDecider))
)

关于你之前尝试的问题说明

  1. 直接修改mat.system.settings.supervisionStrategyClass无效,因为该属性是只读的,且要求传入策略类的全限定名字符串,无法直接赋值决策器实例;
  2. 使用ActorAttributes(supervision.decider)的方向是对的,但需要将其绑定到具体操作/组件上,而非直接关联Materializer——Akka 2.6+的Materializer不再持有监督策略,而是依赖ActorSystem全局配置或具体操作的属性。

内容的提问来源于stack exchange,提问作者rimmi anand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 20:33:10