首页 技术 正文
技术 2022年11月19日
0 收藏 590 点赞 3,038 浏览 4676 个字

akka-stream是多线程non-blocking模式的,一般来说,运算任务提交到另外线程后这个线程就会在当前程序控制之外自由运行了。任何时候如果需要终止运行中的数据流就必须采用一种任务柄(handler)方式来控制在其它线程内运行的任务。这个handler可以在提交运算任务时获取。akka-stream提供了KillSwitch trait来支持这项功能:

/**
* A [[KillSwitch]] allows completion of [[Graph]]s from the outside by completing [[Graph]]s of [[FlowShape]] linked
* to the switch. Depending on whether the [[KillSwitch]] is a [[UniqueKillSwitch]] or a [[SharedKillSwitch]] one or
* multiple streams might be linked with the switch. For details see the documentation of the concrete subclasses of
* this interface.
*/
//#kill-switch
trait KillSwitch {
/**
* After calling [[KillSwitch#shutdown()]] the linked [[Graph]]s of [[FlowShape]] are completed normally.
*/
def shutdown(): Unit
/**
* After calling [[KillSwitch#abort()]] the linked [[Graph]]s of [[FlowShape]] are failed.
*/
def abort(ex: Throwable): Unit
}
//#kill-switch

可以想象:我们必须把这个KillSwitch放在一个流图中间,所以它是一种FlowShape的,这可以从KillSwitch的构建器代码里可以看得到:

object KillSwitches {  /**
* Creates a new [[SharedKillSwitch]] with the given name that can be used to control the completion of multiple
* streams from the outside simultaneously.
*
* @see SharedKillSwitch
*/
def shared(name: String): SharedKillSwitch = new SharedKillSwitch(name) /**
* Creates a new [[Graph]] of [[FlowShape]] that materializes to an external switch that allows external completion
* of that unique materialization. Different materializations result in different, independent switches.
*
* For a Bidi version see [[KillSwitch#singleBidi]]
*/
def single[T]: Graph[FlowShape[T, T], UniqueKillSwitch] =
UniqueKillSwitchStage.asInstanceOf[Graph[FlowShape[T, T], UniqueKillSwitch]] /**
* Creates a new [[Graph]] of [[FlowShape]] that materializes to an external switch that allows external completion
* of that unique materialization. Different materializations result in different, independent switches.
*
* For a Flow version see [[KillSwitch#single]]
*/
def singleBidi[T1, T2]: Graph[BidiShape[T1, T1, T2, T2], UniqueKillSwitch] =
UniqueBidiKillSwitchStage.asInstanceOf[Graph[BidiShape[T1, T1, T2, T2], UniqueKillSwitch]]
...}

akka-stream提供了single,shared,singleBidi三种KillSwitch的构建方式,它们的形状都是FlowShape。KillSwitches.single返回结果类型是Graph[FlowShape[T,T],UniqueKillSwitch]。因为我们需要获取这个KillSwitch的控制柄,所以要用viaMat来可运算化(materialize)这个Graph,然后后选择右边的类型UniqueKillSwitch。这个类型可以控制一个可运算化FlowShape的Graph,如下:

  val source = Source(Stream.from(,)).delay(.second,DelayOverflowStrategy.backpressure)
val sink = Sink.foreach(println)
val killSwitch = source.viaMat(KillSwitches.single)(Keep.right).to(sink).run() scala.io.StdIn.readLine()
killSwitch.shutdown()
println("terminated!")
actorSys.terminate()

当然,也可以用异常方式中断运行:

killSwitch.abort(new RuntimeException("boom!"))

source是一个不停顿每秒发出一个数字的数据源。如上所述:必须把KillSwitch放在source和sink中间形成数据流完整链状。运算这个数据流时返回了handle killSwitch,我们可以使用这个killSwitch来shutdown或abort数据流运算。

KillSwitches.shared构建了一个SharedKillSwitch类型。这个类型可以被用来控制多个FlowShape Graph的终止运算。SharedKillSwitch类型里的flow方法可以返回终止运算的控制柄handler:

 /**
* Returns a typed Flow of a requested type that will be linked to this [[SharedKillSwitch]] instance. By invoking
* [[SharedKillSwitch#shutdown()]] or [[SharedKillSwitch#abort()]] all running instances of all provided [[Graph]]s by this
* switch will be stopped normally or failed.
*
* @tparam T Type of the elements the Flow will forward
* @return A reusable [[Graph]] that is linked with the switch. The materialized value provided is this switch itself.
*/
def flow[T]: Graph[FlowShape[T, T], SharedKillSwitch] = _flow.asInstanceOf[Graph[FlowShape[T, T], SharedKillSwitch]]

用flow构建的SharedKillSwitch实例就像immutable对象,我们可以在多个数据流中插入SharedKillSwitch,然后用这一个共享的handler去终止使用了这个SharedKillSwitch的数据流运算。下面是SharedKillSwitch的使用示范:

  val sharedKillSwitch = KillSwitches.shared("multi-ks")
val source2 = Source(Stream.from()).delay(.second,DelayOverflowStrategy.backpressure) source2.via(sharedKillSwitch.flow).to(sink).run()
source.via(sharedKillSwitch.flow).to(sink).run() scala.io.StdIn.readLine()
killSwitch.shutdown()
sharedKillSwitch.shutdown()

注意:我们先构建了一个SharedKillSwitch实例,然后在source2,source数据通道中间加入了这个实例。因为我们已经获取了sharedKillSwitch控制柄,所以不必理会返回结果,直接用via和to来连接上下游节点(默认为Keep.left)。

还有一个KillSwitches.singleBidi类型,这种KillSwitch是用来终止双流向数据流运算的。我们将在下篇讨论里介绍。

下面是本次示范的源代码:

import akka.stream.scaladsl._
import akka.stream._
import akka.actor._
import scala.concurrent.duration._
object KillSwitchDemo extends App {
implicit val actorSys = ActorSystem("sys")
implicit val ec = actorSys.dispatcher
implicit val mat = ActorMaterializer(
ActorMaterializerSettings(actorSys)
.withInputBuffer(,)
) val source = Source(Stream.from(,)).delay(.second,DelayOverflowStrategy.backpressure)
val sink = Sink.foreach(println)
val killSwitch = source.viaMat(KillSwitches.single)(Keep.right).to(sink).run() val sharedKillSwitch = KillSwitches.shared("multi-ks")
val source2 = Source(Stream.from()).delay(.second,DelayOverflowStrategy.backpressure) source2.via(sharedKillSwitch.flow).to(sink).run()
source.via(sharedKillSwitch.flow).to(sink).run() scala.io.StdIn.readLine()
killSwitch.shutdown()
sharedKillSwitch.shutdown()
println("terminated!")
actorSys.terminate()}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,085
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,560
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,409
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,182
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,819
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,902