经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Scala » 查看文章
akka-streams - 从应用角度学习:basic stream parts
来源:cnblogs  作者:雪川大虫  时间:2020/11/9 16:08:59  对本文有异议

   实际上很早就写了一系列关于akka-streams的博客。但那个时候纯粹是为了了解akka而去学习的,主要是从了解akka-streams的原理为出发点。因为akka-streams是akka系列工具的基础,如:akka-http, persistence-query等都是基于akka-streams的,其实没有真正把akka-streams用起来。这段时间所遇到的一些需求也是通过集合来解决的。不过,现在所处的环境还是逼迫着去真正了解akka-streams的应用场景。现状是这样的:跨入大数据时代,已经有大量的现代IT系统从传统关系数据库转到分布式数据库(非关系数据库)了。不难想象,这些应用的数据操作编程不说截然不同吧,肯定也会有巨大改变。特别是在传统SQL编程中依赖数据关系的join已经不复存在了,groupby、disctict等操作方法也不是所有的分布式数据库都能支持的。而这些操作在具体的数据呈现和数据处理中又是不可缺少的。当然,有很多需求可以通过集合来满足,但涉及到大数据处理我想最好还是通过流处理来实现,因为流处理stream-processing的其中一项特点就是能够在有限的内存空间里处理无限量的数据。所以流处理应该是分布式数据处理的理想方式了。这是这次写akka-streams的初衷:希望能通过akka-streams来实现分布式数据处理编程。

先从基本流部件basic stream parts开始,即source,flow,sink。这几个部件可以组合成一个所谓线性流linear-stream。一个流对数据的处理包括两部分:1、对流中元素进行转变,如:source:Source[Int,NotUsed] = Source(1 to 10).map(i => i.toString),把流里的所有Int转变成String、2、对流内元素进行计算得出运算结果,如:sink: Sink[Int,Future[Int]] = Sink.fold(0)(_ + _)。当我们run这个sink后得出Future[Int],如:res: Future[Int] = src.runWith(sink)。这两项对流元素的操作所产生的结果不同:元素转换得到动态流动的一串元素、运算元素得到一个静态值,这个运算值materialized-value只能在Sink里获取。即使有这样的表示方式:Source[Int,Future[Int]],这是个迷惑,这个运算值只能通过自定义的graph才能得到,也就是说基本组件是没这个功能的。举个具体的例子吧:val source: Source[Int, Promise[Option[Int]]] = Source.maybe[Int] 这个表达式貌似可以在Source方获取运算值,再看看Source.maybe[Int]:

  1. def maybe[T]: Source[T, Promise[Option[T]]] =
  2. Source.fromGraph(MaybeSource.asInstanceOf[Graph[SourceShape[T], Promise[Option[T]]]])

可以看出这个Source.maybe是从graph构建的。

上面这个例子里用一个Source对接一个Sink已经组成了一个完整的流,那么Flow是用来干什么的呢?由于运算值是无法当作流元素传递的,Flow只能是用来对Source传下来的元素进行转换后再传递给Sink,也就是说Flow是由一个或多个处理环节构成的。用Flow来分步实现功能是流处理实现并行运算的基本方式,如:

  1. Source(1 to 10).async.via(Flow[Int].map(i => i + 1)).async.runWith(sink)

用async把这个流分割成3个运算发送给3个actor去同时运算。乍看之下map好像是个Flow,它们的作用也似乎相同,也可以对接Source。如:Source(1 to 10).map(_ + 1)。但map和Flow还是有分别的,从类型款式来看Flow[In,Out,M]比起map[A,B]多出来了M,运算值。所以via(map(_.toString))无法匹配类型。那么对于定义带有预先处理环节的Sink就必须用Flow来实现了:ex_sink = Flow[Int].map(_ + 1).to(sink)。

虽然运算值不能像流元素一样流动,但akka-streams提供了机制让用户选择是否返回某个节点的运算值M。系统默认只选择最最左边节点的M,如:

  1. // A source that can be signalled explicitly from the outside
  2. val source: Source[Int, Promise[Option[Int]]] = Source.maybe[Int]
  3. // A flow that internally throttles elements to 1/second, and returns a Cancellable
  4. // which can be used to shut down the stream
  5. val flow: Flow[Int, Int, Cancellable] = throttler
  6. // A sink that returns the first element of a stream in the returned Future
  7. val sink: Sink[Int, Future[Int]] = Sink.head[Int]
  8. val stream: RunnableGraph[(Cancellable, Future[Int])] =
  9. source.viaMat(flow)(Keep.right).toMat(sink)(Keep.both)
  10. val stream1: RunnableGraph[(Promise[Option[Int]], Cancellable, Future[Int])] =
  11. source.viaMat(flow)(Keep.both).toMat(sink)(Keep.both)

运算值M可以通过viaMat,toMat选择,然后stream.run()获取。akka-streams提供了简便一点的运算方式runWith:指定runWith参数流组件的M为最终运算值。如:

  1. // Using runWith will always give the materialized values of the stages added
  2. // by runWith() itself
  3. val r4: Future[Int] = source.via(flow).runWith(sink)
  4. val r5: Promise[Option[Int]] = flow.to(sink).runWith(source)
  5. val r6: (Promise[Option[Int]], Future[Int]) = flow.runWith(source, sink)

值得注意的是:我们可以分别从Source,Sink,Flow开始针对Source runWith(Sink), Sink runWith(Source)及Flow runWith (Source,Sink)。用基础流组件Source,Flow,Sink构成的流是直线型的。也就是说从Source流出的元素会一个不漏的经过Flow进入Sink,不能多也不能少。可能Source.filter会产生疑惑,不过看看filter函数定义就明白了:

  1. def filter(p: Out => Boolean): Repr[Out] = via(Filter(p))
  2. @InternalApi private[akka] final case class Filter[T](p: T => Boolean) extends SimpleLinearGraphStage[T] {
  3. override def initialAttributes: Attributes = DefaultAttributes.filter
  4. override def toString: String = "Filter"
  5. override def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
  6. new GraphStageLogic(shape) with OutHandler with InHandler {
  7. def decider = inheritedAttributes.mandatoryAttribute[SupervisionStrategy].decider
  8. private var buffer: OptionVal[T] = OptionVal.none
  9. override def preStart(): Unit = pull(in)
  10. override def onPush(): Unit =
  11. try {
  12. val elem = grab(in)
  13. if (p(elem))
  14. if (isAvailable(out)) {
  15. push(out, elem)
  16. pull(in)
  17. } else
  18. buffer = OptionVal.Some(elem)
  19. else pull(in)
  20. } catch {
  21. case NonFatal(ex) =>
  22. decider(ex) match {
  23. case Supervision.Stop => failStage(ex)
  24. case _ => pull(in)
  25. }
  26. }
  27. override def onPull(): Unit =
  28. buffer match {
  29. case OptionVal.Some(value) =>
  30. push(out, value)
  31. buffer = OptionVal.none
  32. if (!isClosed(in)) pull(in)
  33. else completeStage()
  34. case _ => // already pulled
  35. }
  36. override def onUpstreamFinish(): Unit =
  37. if (buffer.isEmpty) super.onUpstreamFinish()
  38. // else onPull will complete
  39. setHandlers(in, out, this)
  40. }
  41. }

怎样?够复杂的了吧。很明显,复杂点的流处理需要根据上游元素内容来维护内部状态从而重新构建向下游发送元素的机制。如果想实现join,groupby,distict这些功能就必然对流动元素除转换之外还需要进行增减操作。这项需求可能还必须留在后面的sream-graph章节中讨论解决方案了。不过临时解决方法可以通过运算值M来实现。因为M可以是一个集合,在构建这个M集合时是可以对集合元素进行增减的,下面这段代码示范了一种cassandra数据表groupby的效果:

  1. def getVouchers(terminalid: String, susp: Boolean)(implicit classicSystem: ActorSystem) = {
  2. implicit val session = CassandraSessionRegistry(classicSystem).sessionFor("alpakka.cassandra")
  3. implicit val ec = classicSystem.dispatcher
  4. var stmt = "select * from pos_on_cloud.txn_log where terminal = ? and txndate = ?"
  5. if (susp) stmt = "select * from pos_on_cloud.txn_hold where terminal = ? and txndate = ?"
  6. val source = session.select(stmt,terminalid,LocalDate.now.format(DateTimeFormatter.ofPattern("yyyyMMdd")))
  7. val sink = Sink.fold[List[TxnItem],TxnItem](List[TxnItem]()){(acc,txn) =>
  8. if (acc.isEmpty) txn.copy(price = 1) :: acc
  9. else
  10. if (acc.head.num == txn.num) {
  11. if (txn.salestype == SALESTYPE.itm &&
  12. txn.txntype == TXNTYPE.sales) {
  13. val nacc = acc.head.copy(
  14. price = acc.head.price + 1,
  15. qty = acc.head.qty + txn.qty,
  16. amount = acc.head.amount + txn.amount,
  17. dscamt = acc.head.dscamt + txn.dscamt
  18. )
  19. nacc :: acc.drop(1)
  20. } else acc
  21. }
  22. else txn :: acc
  23. }
  24. for {
  25. vchs <- source.map(TxnItem.fromCqlRow).toMat(sink)(Keep.right).run()
  26. _ <- session.close(ec)
  27. } yield vchs
  28. }

当然,基本流组件在流模式数据库读写方面还是比较高效的,如:

  1. def futTxns(items: Seq[TxnItem]): Future[Seq[TxnItem]] = Source(items.toSeq)
  2. .via(
  3. CassandraFlow.create(CassandraWriteSettings.defaults,
  4. CQLScripts.insertTxns,
  5. statementBinder)
  6. )
  7. .runWith(Sink.seq)

 

 

原文链接:http://www.cnblogs.com/tiger-xc/p/13624832.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号