Spray + Akka高性能异步IO并发
http://ju.outofmemory.cn/entry/70913
http://www.jdon.com/concurrent/spray-akka.html
如何使用Java建立像Node.js那样非堵塞异步事件并发IO服务器呢?Spray是基于NIO2高并发框架,虽然Tomcat 8也是基于NIO2,但是Spary的线程数要低得到,降低CPU上下文切换的负载;Akka和其Mysql库包都是相同线程执行上下文( execution context),因为在非堵塞前提下,性能拼的就不是线程数目越多越好,正好相反,线程数目越低,越接近理论理论最佳点。
启动设置
为了启动Spary和Akka,需要一个main启动函数,在main函数中,我们创建一个Actor系统:
ActorSystem system = ActorSystem.create("system");
ActorRef listener = system.actorOf(Props.create(HttpActor.class), "httpActor");
listener是使用Actor用来处理Http请求。然后要设定监听Http的端口:
InetSocketAddress endpoint = new InetSocketAddress(3000);
int backlog = 100;
List<Inet.SocketOption> options = JavaConversions.asScalaBuffer(new ArrayList<Inet.SocketOption>()).toList();
Option<ServerSettings> settings = scala.Option.empty();
最后,绑定Actor到监听的Http端口:
Bind bind = new Http.Bind(listener, endpoint, backlog, options, settings, sslEngineProvider);
IO.apply(spray.can.Http$.MODULE$, system).tell(bind, ActorRef.noSender());
整个main函数主要代码如下:
public static final ActorSystem system = ActorSystem.create("system");
public static void main(String[] args) {
...
ActorRef listener = system.actorOf(Props.create(HttpActor.class), "httpActor");
InetSocketAddress endpoint = new InetSocketAddress(3000);
int backlog = 100;
List<Inet.SocketOption> options = JavaConversions.asScalaBuffer(new ArrayList<Inet.SocketOption>()).toList();
Option<ServerSettings> settings = scala.Option.empty();
ServerSSLEngineProvider sslEngineProvider = null;
Bind bind = new Http.Bind(listener, endpoint, backlog, options, settings, sslEngineProvider);
IO.apply(spray.can.Http$.MODULE$, system).tell(bind, ActorRef.noSender());
...
}
设置好启动函数以后,下面是真正开始在Actor里处理进来Http请求了。
请求处理器
首先,我们因为使用的是原生Java代码,不是Scala,因此需要将Scala集成到Java中,可能比较丑陋,可以用专门类包装一下,引入Scala的Http协议:
HttpProtocol HTTP_1_1 = HttpProtocols.HTTP$div1$u002E1();
Http Actor为了响应Http请求做三件事,第一件是创建一个路由router,这样能够根据请求URL:http://xxx/path中不同的/path分别处理:
Router router = partitionAndCreateRouter();
第二件是处理新的连接,告诉Spray这个actor不仅接受Http连接,也处理实际http连接:
}).match(Tcp.Connected.class, r ->{
sender().tell(new Http.Register(self(), Http.EmptyFastPath$.MODULE$), self());//tell that connection will be handled here!
})
第三件事就是处理实际的Http连接,将http请求委托给另外一个actor处理。
.match(HttpRequest.class, r -> {
int id = Constants.ID.getAndIncrement();
String path = String.valueOf(r.uri().path());
if("/sell".equals(path)){
... //逻辑处理
}else if("/buy".equals(path)){
... //逻辑处理
}else{
handleUnexpected(r);
}
})
整个HttpActor代码如下,业务逻辑以买卖为模型:
private static class HttpActor extends AbstractActor {
private static final HttpProtocol HTTP_1_1 = HttpProtocols.HTTP$div1$u002E1();
public HttpActor() {
final Router router = partitionAndCreateRouter();
receive(ReceiveBuilder
.match(HttpRequest.class, r -> {
int id = Constants.ID.getAndIncrement();
String path = String.valueOf(r.uri().path());
if("/sell".equals(path)){
String productId = r.uri().query().get("productId").get();
...
SalesOrder so = new SalesOrder(price, productId, quantity, id);
so.setSeller(new Seller(who));
router.route(so, self());
replyOK(id);
}else if("/buy".equals(path)){
...
}else{
handleUnexpected(r);
}
}).match(Tcp.Connected.class, r ->{
sender().tell(new Http.Register(self(), Http.EmptyFastPath$.MODULE$), self());//tell that connection will be handled here!
}).build());
}
该案例使用的驱动包有: Akka, Spray, and this Mysql async driver., 整个源码下载:GitHub
Actor模型教程
NIO原理与应用
Spray + Akka高性能异步IO并发相关推荐
- akka mysql_Spray + Akka高性能异步IO并发
Spray + Akka高性能异步IO并发 如何使用Java建立像Node.js那样非堵塞异步事件并发IO服务器呢?Spray是基于NIO2高并发框架,虽然Tomcat 8也是基于NIO2,但是Spa ...
- 高性能异步IO机制:IO_URING
高性能异步IO机制:IO_URING 一.前言 1.1 异步IO机制 Linux内核提供的IO机制大都是同步实现的,如常规的read/write/send/recv等系统调用.同步IO机制存在着一定的 ...
- Python 高级编程和异步IO并发编程 --13_5 ThreadPoolExecutor 和asyncio完成阻塞io请求
# 使用多线程:在协程中集成阻塞io import asyncio import socket import time from urllib.parse import urlparse from c ...
- Python 高级编程和异步IO并发编程 --13_4 call_soon,call_at,call_soon_threadsafe
import asynciodef callback(sleep_time):print("sleep {} success".format(sleep_time))if __na ...
- Python 高级编程和异步IO并发编程 --13_7 futur和task
task是future的一个子类,task是协程和future之间的桥梁 task启动协程,保持和线程池的接口一致
- Python 高级编程和异步IO并发编程 --13_6 asyncio模拟http请求
# asyncio 没有提供http协议的接口 import asyncio import time from urllib.parse import urlparseasync def get_ur ...
- Python 高级编程和异步IO并发编程 --12_7 生成器进阶- yield from
# Python 3.3新加了yield from语法 from itertools import chain # chain可以将迭代的类型给连接起来,直接做一个for循环 my_list = [1 ...
- 【进阶】 --- 多线程、多进程、异步IO实用例子
[进阶] --- 多线程.多进程.异步IO实用例子:https://blog.csdn.net/lu8000/article/details/82315576 python之爬虫_并发(串行.多线程. ...
- react性能优化方案_React灵敏且性能卓越的Spray + Akka解决方案,以“在Java和Node.js中发挥并发性和性能”...
react性能优化方案 在我以前的文章中,我研究了一个虚拟的交易引擎,并将基于Java的阻止解决方案与基于Node.js的非阻止解决方案进行了比较. 在文章的结尾,我写道: 我怀疑随着Node.js的 ...
最新文章
- 目前最全面深入的Linux设备驱动程序著作
- 渗透脚本快速生成工具Intersect
- Idea debugger 无法启动-unable to open debugger port , java.net.SocketException socket closed
- 数据下载工作笔记三:脚本
- SIFT算法原理(不带公式)
- MinGw+Msys搭建环境 编译ffmpeg
- ubuntu共享文件夹文件看不到_实验08:轻松搭建文件夹共享
- css Flex布局(一)
- 第四篇、Python文件处理
- sosoapi初次接触
- 梁宁-产品思维30讲-机会判断-点线面体的战略选择
- android平板和ipad区别,iPad和安卓平板差距大吗?亲身经历告诉你,平板该如何挑选...
- 计算机考研和软件的区别吗,考研考计算机与考软件有什么区别
- 基于机器学习和深度学习的图数据异常检测综述
- John F. Kennedy的就职演说(在线收听)
- semantic_slam环境配置
- JavaScript奇淫技巧:按键精灵
- c语言 写播放器,C语言实现Mini-Cooledit音频播放器(13页)-原创力文档
- number-precision--使用/实例
- 老虎证券国际完成5亿C轮融资 估值10.6亿美元成新独角兽
热门文章
- Java+MyEclipse+Tomcat (三)配置MySQL及查询数据显示在JSP网页中
- 【数据结构与算法】之深入解析“有效的括号”的求解思路与算法示例
- Python将秒转换为 时分秒 的格式
- 2014\Province_C_C++_B\3 李白打酒
- Vue.js项目新建及目录结构分析
- 操作ROS松灵机器人步骤及遇到的问题
- 【Linux网络编程】无连接和面向连接协议
- 【Linux】一步一步学Linux——crontab命令(132)
- 【C语言】控制台窗口图形界面编程(二)窗口信息和填充缓冲区
- android快速打包工具下载,【Android】多渠道打包,其实可以更快