Akka(43): Http:SSE-Server Sent Event - 服务端主推消息

2024-04-09 04:48

本文主要是介绍Akka(43): Http:SSE-Server Sent Event - 服务端主推消息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

   因为我了解Akka-http的主要目的不是为了有关Web-Server的编程,而是想实现一套系统集成的api,所以也需要考虑由服务端主动向客户端发送指令的应用场景。比如一个零售店管理平台的服务端在完成了某些数据更新后需要通知各零售门市客户端下载最新数据。虽然Akka-http也提供对websocket协议的支持,但websocket的网络连接是双向恒久的,适合频繁的问答交互式服务端与客户端的交流,消息结构也比较零碎。而我们面临的可能是批次型的大量数据库数据交换,只需要简单的服务端单向消息就行了,所以websocket不太合适,而Akka-http的SSE应该比较适合我们的要求。SSE模式的基本原理是服务端统一集中发布消息,各客户端持久订阅服务端发布的消息并从消息的内容中筛选出属于自己应该执行的指令,然后进行相应的处理。客户端接收SSE是在一个独立的线程里不断进行的,不会影响客户端当前的运算流程。当收到有用的消息后就会调用一个业务功能函数作为后台异步运算任务。

服务端的SSE发布是以Source[ServerSentEvent,NotUsed]来实现的。ServerSentEvent类型定义如下:

/*** Representation of a server-sent event. According to the specification, an empty data field designates an event* which is to be ignored which is useful for heartbeats.** @param data data, may span multiple lines* @param eventType optional type, must not contain \n or \r* @param id optional id, must not contain \n or \r* @param retry optional reconnection delay in milliseconds*/
final case class ServerSentEvent(data:      String,eventType: Option[String] = None,id:        Option[String] = None,retry:     Option[Int]    = None) {...}

这个类型的参数代表事件消息的数据结构。用户可以根据实际需要充分利用这个数据结构来传递消息。服务端是通过complete以SeverSentEvent类为元素 的Source来进行SSE的,如下:

    import akka.http.scaladsl.marshalling.sse.EventStreamMarshalling._complete {Source.tick(2.seconds, 2.seconds, NotUsed).map( _ => processToServerSentEvent).keepAlive(1.second, () => ServerSentEvent.heartbeat)}

以上代码代表服务端定时运算processToServerSentEvent返回ServerSentEvent类型结果后发布给所有订阅的客户端。我们用一个函数processToServerSentEvent模拟重复运算的业务功能:

  private def processToServerSentEvent: ServerSentEvent = {Thread.sleep(3000)   //processing delayServerSentEvent(SyncFiles.fileToSync)}

这个函数模拟发布事件数据是某种业务运算结果,在这里代表客户端需要下载文件名称。我们用客户端request来模拟设定这个文件名称:

  object SyncFiles {var fileToSync: String = ""}private def route = {import Directives._import akka.http.scaladsl.marshalling.sse.EventStreamMarshalling._def syncRequests =pathPrefix("sync") {pathSingleSlash {post {parameter("file") { filename =>complete {SyncFiles.fileToSync = filenames"set download file to : $filename"}}}}}

客户端订阅SSE的方式如下:

    import akka.http.scaladsl.unmarshalling.sse.EventStreamUnmarshalling._import system.dispatcherHttp().singleRequest(Get("http://localhost:8011/events")).flatMap(Unmarshal(_).to[Source[ServerSentEvent, NotUsed]]).foreach(_.runForeach(se => downloadFiles(se.data)))

每当客户端收到SSE后即运行downloadFiles(filename)函数。downloadFiles函数定义:

  def downloadFiles(file: String) = {Thread.sleep(3000)   //process delayif (file != "")println(s"Try to download $file")}

下面是客户端程序的测试运算步骤:

    scala.io.StdIn.readLine()println("do some thing ...")Http().singleRequest(HttpRequest(method=HttpMethods.POST,uri = "http://localhost:8011/sync/?file=Orders")).onSuccess {case msg => println(msg)}scala.io.StdIn.readLine()println("do some other things ...")Http().singleRequest(HttpRequest(method=HttpMethods.POST,uri = "http://localhost:8011/sync/?file=Items")).onSuccess {case msg => println(msg)}

运算结果:

do some thing ...
HttpResponse(200 OK,List(Server: akka-http/10.0.10, Date: Fri, 15 Dec 2017 05:50:52 GMT),HttpEntity.Strict(text/plain; charset=UTF-8,set download file to : Orders),HttpProtocol(HTTP/1.1))
Try to download Orders
Try to download Ordersdo some other things ...
HttpResponse(200 OK,List(Server: akka-http/10.0.10, Date: Fri, 15 Dec 2017 05:51:02 GMT),HttpEntity.Strict(text/plain; charset=UTF-8,set download file to : Items),HttpProtocol(HTTP/1.1))
Try to download Orders
Try to download Orders
Try to download Items
Try to download ItemsTry to download ItemsProcess finished with exit code 0

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

服务端:

import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import scala.concurrent.duration.DurationInt
import akka.http.scaladsl.model.sse.ServerSentEventobject SSEServer {def main(args: Array[String]): Unit = {implicit val system = ActorSystem()implicit val mat    = ActorMaterializer()Http().bindAndHandle(route, "localhost", 8011)scala.io.StdIn.readLine()system.terminate()}object SyncFiles {var fileToSync: String = ""}private def route = {import Directives._import akka.http.scaladsl.marshalling.sse.EventStreamMarshalling._def syncRequests =pathPrefix("sync") {pathSingleSlash {post {parameter("file") { filename =>complete {SyncFiles.fileToSync = filenames"set download file to : $filename"}}}}}def events =path("events") {get {complete {Source.tick(2.seconds, 2.seconds, NotUsed).map( _ => processToServerSentEvent).keepAlive(1.second, () => ServerSentEvent.heartbeat)}}}syncRequests ~ events}private def processToServerSentEvent: ServerSentEvent = {Thread.sleep(3000)   //processing delayServerSentEvent(SyncFiles.fileToSync)}
}

客户端:

import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.client.RequestBuilding.Get
import akka.http.scaladsl.model.HttpMethods
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source
import akka.http.scaladsl.model.sse.ServerSentEvent
import akka.http.scaladsl.model._object SSEClient {def downloadFiles(file: String) = {Thread.sleep(3000)   //process delayif (file != "")println(s"Try to download $file")}def main(args: Array[String]): Unit = {implicit val system = ActorSystem()implicit val mat    = ActorMaterializer()import akka.http.scaladsl.unmarshalling.sse.EventStreamUnmarshalling._import system.dispatcherHttp().singleRequest(Get("http://localhost:8011/events")).flatMap(Unmarshal(_).to[Source[ServerSentEvent, NotUsed]]).foreach(_.runForeach(se => downloadFiles(se.data)))scala.io.StdIn.readLine()println("do some thing ...")Http().singleRequest(HttpRequest(method=HttpMethods.POST,uri = "http://localhost:8011/sync/?file=Orders")).onSuccess {case msg => println(msg)}scala.io.StdIn.readLine()println("do some other things ...")Http().singleRequest(HttpRequest(method=HttpMethods.POST,uri = "http://localhost:8011/sync/?file=Items")).onSuccess {case msg => println(msg)}scala.io.StdIn.readLine()system.terminate()}
}






这篇关于Akka(43): Http:SSE-Server Sent Event - 服务端主推消息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/887211

相关文章

SQL server数据库如何下载和安装

《SQLserver数据库如何下载和安装》本文指导如何下载安装SQLServer2022评估版及SSMS工具,涵盖安装配置、连接字符串设置、C#连接数据库方法和安全注意事项,如混合验证、参数化查... 目录第一步:打开官网下载对应文件第二步:程序安装配置第三部:安装工具SQL Server Manageme

C#连接SQL server数据库命令的基本步骤

《C#连接SQLserver数据库命令的基本步骤》文章讲解了连接SQLServer数据库的步骤,包括引入命名空间、构建连接字符串、使用SqlConnection和SqlCommand执行SQL操作,... 目录建议配合使用:如何下载和安装SQL server数据库-CSDN博客1. 引入必要的命名空间2.

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

java向微信服务号发送消息的完整步骤实例

《java向微信服务号发送消息的完整步骤实例》:本文主要介绍java向微信服务号发送消息的相关资料,包括申请测试号获取appID/appsecret、关注公众号获取openID、配置消息模板及代码... 目录步骤1. 申请测试系统2. 公众号账号信息3. 关注测试号二维码4. 消息模板接口5. Java测试

springboot如何通过http动态操作xxl-job任务

《springboot如何通过http动态操作xxl-job任务》:本文主要介绍springboot如何通过http动态操作xxl-job任务的问题,具有很好的参考价值,希望对大家有所帮助,如有错... 目录springboot通过http动态操作xxl-job任务一、maven依赖二、配置文件三、xxl-

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w

Maven 配置中的 <mirror>绕过 HTTP 阻断机制的方法

《Maven配置中的<mirror>绕过HTTP阻断机制的方法》:本文主要介绍Maven配置中的<mirror>绕过HTTP阻断机制的方法,本文给大家分享问题原因及解决方案,感兴趣的朋友一... 目录一、问题场景:升级 Maven 后构建失败二、解决方案:通过 <mirror> 配置覆盖默认行为1. 配置示

Linux中修改Apache HTTP Server(httpd)默认端口的完整指南

《Linux中修改ApacheHTTPServer(httpd)默认端口的完整指南》ApacheHTTPServer(简称httpd)是Linux系统中最常用的Web服务器之一,本文将详细介绍如何... 目录一、修改 httpd 默认端口的步骤1. 查找 httpd 配置文件路径2. 编辑配置文件3. 保存

Python FastMCP构建MCP服务端与客户端的详细步骤

《PythonFastMCP构建MCP服务端与客户端的详细步骤》MCP(Multi-ClientProtocol)是一种用于构建可扩展服务的通信协议框架,本文将使用FastMCP搭建一个支持St... 目录简介环境准备服务端实现(server.py)客户端实现(client.py)运行效果扩展方向常见问题结