百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

swoole-src异步、并行、高性能网络通信引擎

ccwgpt 2024-09-29 10:03 23 浏览 0 评论

Swoole是一个为PHP用C和C++编写的基于事件的高性能异步&协程并行网络通信引擎

?事件驱动

Swoole中的网络请求处理是基于事件的,并且充分利用了底层的epoll / kqueue实现,使得为数百万个请求提供服务变得非常容易。

Swoole4使用全新的协程内核引擎,现在它拥有一个全职的开发团队,因此我们正在进入PHP历史上前所未有的时期,为性能的高速提升提供了独一无二的可能性。

??协程

Swoole4或更高版本拥有高可用性的内置协程,您可以使用完全同步的代码来实现异步性能,PHP代码没有任何额外的关键字,底层会自动进行协程调度。

开发者可以将协程理解为超轻量级的线程, 你可以非常容易地在一个进程中创建成千上万个协程。

MySQL客户端

并发1万个请求从MySQL读取海量数据仅需要0.2秒

$s = microtime(true);
for ($c = 100; $c--;) {
 go(function () {
 $mysql = new Swoole\Coroutine\MySQL;
 $mysql->connect([
 'host' => '127.0.0.1',
 'user' => 'root',
 'password' => 'root',
 'database' => 'test'
 ]);
 $statement = $mysql->prepare('SELECT * FROM `user`');
 for ($n = 100; $n--;) {
 $result = $statement->execute();
 assert(count($result) > 0);
 }
 });
}
Swoole\Event::wait();
echo 'use ' . (microtime(true) - $s) . ' s';

混合服务器

你可以在一个事件循环上创建多个服务:TCP,HTTP,Websocket和HTTP2,并且能轻松承载上万请求。

function tcp_pack(string $data): string
{
 return pack('N', strlen($data)) . $data;
}
function tcp_unpack(string $data): string
{
 return substr($data, 4, unpack('N', substr($data, 0, 4))[1]);
}
$tcp_options = [
 'open_length_check' => true,
 'package_length_type' => 'N',
 'package_length_offset' => 0,
 'package_body_offset' => 4
];
$server = new Swoole\WebSocket\Server('127.0.0.1', 9501, SWOOLE_BASE);
$server->set(['open_http2_protocol' => true]);
// http && http2
$server->on('request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
 $response->end('Hello ' . $request->rawcontent());
});
// websocket
$server->on('message', function (Swoole\WebSocket\Server $server, Swoole\WebSocket\Frame $frame) {
 $server->push($frame->fd, 'Hello ' . $frame->data);
});
// tcp
$tcp_server = $server->listen('127.0.0.1', 9502, SWOOLE_TCP);
$tcp_server->set($tcp_options);
$tcp_server->on('receive', function (Swoole\Server $server, int $fd, int $reactor_id, string $data) {
 $server->send($fd, tcp_pack('Hello ' . tcp_unpack($data)));
});
$server->start();

多种客户端

不管是DNS查询抑或是发送请求和接收响应,都是协程调度的,不会产生任何阻塞。

go(function () {
 // http
 $http_client = new Swoole\Coroutine\Http\Client('127.0.0.1', 9501);
 assert($http_client->post('/', 'Swoole Http'));
 var_dump($http_client->body);
 // websocket
 $http_client->upgrade('/');
 $http_client->push('Swoole Websocket');
 var_dump($http_client->recv()->data);
});
go(function () {
 // http2
 $http2_client = new Swoole\Coroutine\Http2\Client('localhost', 9501);
 $http2_client->connect();
 $http2_request = new Swoole\Http2\Request;
 $http2_request->method = 'POST';
 $http2_request->data = 'Swoole Http2';
 $http2_client->send($http2_request);
 $http2_response = $http2_client->recv();
 var_dump($http2_response->data);
});
go(function () use ($tcp_options) {
 // tcp
 $tcp_client = new Swoole\Coroutine\Client(SWOOLE_TCP);
 $tcp_client->set($tcp_options);
 $tcp_client->connect('127.0.0.1', 9502);
 $tcp_client->send(tcp_pack('Swoole Tcp'));
 var_dump(tcp_unpack($tcp_client->recv()));
});

通道

通道(Channel)是协程之间通信交换数据的唯一渠道, 而协程+通道的开发组合即为著名的CSP编程模型。

在Swoole开发中,Channel常用于连接池的实现和协程并发的调度。

连接池最简示例

在以下示例中,我们并发了一千个redis请求,通常的情况下,这已经超过了Redis最大的连接数,将会抛出连接异常, 但基于Channel实现的连接池可以完美地调度请求,开发者就无需担心连接过载。

class RedisPool
{
 /**@var \Swoole\Coroutine\Channel */
 protected $pool;
 /**
 * RedisPool constructor.
 * @param int $size max connections
 */
 public function __construct(int $size = 100)
 {
 $this->pool = new \Swoole\Coroutine\Channel($size);
 for ($i = 0; $i < $size; $i++) {
 $redis = new \Swoole\Coroutine\Redis();
 $res = $redis->connect('127.0.0.1', 6379);
 if ($res == false) {
 throw new \RuntimeException("failed to connect redis server.");
 } else {
 $this->put($redis);
 }
 }
 }
 public function get(): \Swoole\Coroutine\Redis
 {
 return $this->pool->pop();
 }
 public function put(\Swoole\Coroutine\Redis $redis)
 {
 $this->pool->push($redis);
 }
 public function close(): void
 {
 $this->pool->close();
 $this->pool = null;
 }
}
go(function () {
 $pool = new RedisPool();
 // max concurrency num is more than max connections
 // but it's no problem, channel will help you with scheduling
 for ($c = 0; $c < 1000; $c++) {
 go(function () use ($pool, $c) {
 for ($n = 0; $n < 100; $n++) {
 $redis = $pool->get();
 assert($redis->set("awesome-{$c}-{$n}", 'swoole'));
 assert($redis->get("awesome-{$c}-{$n}") === 'swoole');
 assert($redis->delete("awesome-{$c}-{$n}"));
 $pool->put($redis);
 }
 });
 }
});

生产和消费

Swoole的部分客户端实现了defer机制来进行并发,但你依然可以用协程和通道的组合来灵活地实现它。

go(function () {
 // User: I need you to bring me some information back.
 // Channel: OK! I will be responsible for scheduling.
 $channel = new Swoole\Coroutine\Channel;
 go(function () use ($channel) {
 // Coroutine A: Ok! I will show you the github addr info
 $addr_info = Co::getaddrinfo('github.com');
 $channel->push(['A', json_encode($addr_info, JSON_PRETTY_PRINT)]);
 });
 go(function () use ($channel) {
 // Coroutine B: Ok! I will show you what your code look like
 $mirror = Co::readFile(__FILE__);
 $channel->push(['B', $mirror]);
 });
 go(function () use ($channel) {
 // Coroutine C: Ok! I will show you the date
 $channel->push(['C', date(DATE_W3C)]);
 });
 for ($i = 3; $i--;) {
 list($id, $data) = $channel->pop();
 echo "From {$id}:\n {$data}\n";
 }
 // User: Amazing, I got every information at earliest time!
});

定时器

$id = Swoole\Timer::tick(100, function () {
 echo "?? Do something...\n";
});
Swoole\Timer::after(500, function () use ($id) {
 Swoole\Timer::clear($id);
 echo "? Done\n";
});
Swoole\Timer::after(1000, function () use ($id) {
 if (!Swoole\Timer::exists($id)) {
 echo "? All right!\n";
 }
});

使用协程方式

go(function () {
 $i = 0;
 while (true) {
 Co::sleep(0.1);
 echo " Do something...\n";
 if (++$i === 5) {
 echo " Done\n";
 break;
 }
 }
 echo " All right!\n";
});

命名空间

Swoole提供了多种类命名规则以满足不同开发者的爱好

  1. 符合PSR规范的命名空间风格
  2. 便于键入的下划线风格
  3. 协程类短名风格

强大的运行时钩子

在最新版本的Swoole中,我们添加了一项新功能,使PHP原生的同步网络库一键化成为协程库。

只需在脚本顶部调用Swoole\Runtime::enableCoroutine()方法并使用php-redis,并发1万个请求从Redis读取数据仅需0.1秒!

Swoole\Runtime::enableCoroutine();
$s = microtime(true);
for ($c = 100; $c--;) {
 go(function () {
 ($redis = new Redis)->connect('127.0.0.1', 6379);
 for ($n = 100; $n--;) {
 assert($redis->get('awesome') === 'swoole');
 }
 });
}
Swoole\Event::wait();
echo 'use ' . (microtime(true) - $s) . ' s';

调用它之后,Swoole内核将替换ZendVM中的Stream函数指针,如果使用基于php_stream的扩展,则所有套接字操作都可以在运行时动态转换为协程调度的异步IO。

你可以在一秒钟里做多少事?

睡眠1万次,读取,写入,检查和删除文件1万次,使用PDO和MySQLi与数据库通信1万次,创建TCP服务器和多个客户端相互通信1万次,创建UDP服务器和多个客户端到相互通信1万次......一切都在一个进程中完美完成!

Swoole\Runtime::enableCoroutine();
$s = microtime(true);
// i just want to sleep...
for ($c = 100; $c--;) {
 go(function () {
 for ($n = 100; $n--;) {
 usleep(1000);
 }
 });
}
// 10k file read and write
for ($c = 100; $c--;) {
 go(function () use ($c) {
 $tmp_filename = "/tmp/test-{$c}.php";
 for ($n = 100; $n--;) {
 $self = file_get_contents(__FILE__);
 file_put_contents($tmp_filename, $self);
 assert(file_get_contents($tmp_filename) === $self);
 }
 unlink($tmp_filename);
 });
}
// 10k pdo and mysqli read
for ($c = 50; $c--;) {
 go(function () {
 $pdo = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', 'root', 'root');
 $statement = $pdo->prepare('SELECT * FROM `user`');
 for ($n = 100; $n--;) {
 $statement->execute();
 assert(count($statement->fetchAll()) > 0);
 }
 });
}
for ($c = 50; $c--;) {
 go(function () {
 $mysqli = new Mysqli('127.0.0.1', 'root', 'root', 'test');
 $statement = $mysqli->prepare('SELECT `id` FROM `user`');
 for ($n = 100; $n--;) {
 $statement->bind_result($id);
 $statement->execute();
 $statement->fetch();
 assert($id > 0);
 }
 });
}
// php_stream tcp server & client with 12.8k requests in single process
function tcp_pack(string $data): string
{
 return pack('n', strlen($data)) . $data;
}
function tcp_length(string $head): int
{
 return unpack('n', $head)[1];
}
go(function () {
 $ctx = stream_context_create(['socket' => ['so_reuseaddr' => true, 'backlog' => 128]]);
 $socket = stream_socket_server(
 'tcp://0.0.0.0:9502',
 $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $ctx
 );
 if (!$socket) {
 echo "$errstr ($errno)\n";
 } else {
 $i = 0;
 while ($conn = stream_socket_accept($socket, 1)) {
 stream_set_timeout($conn, 5);
 for ($n = 100; $n--;) {
 $data = fread($conn, tcp_length(fread($conn, 2)));
 assert($data === "Hello Swoole Server #{$n}!");
 fwrite($conn, tcp_pack("Hello Swoole Client #{$n}!"));
 }
 if (++$i === 128) {
 fclose($socket);
 break;
 }
 }
 }
});
for ($c = 128; $c--;) {
 go(function () {
 $fp = stream_socket_client("tcp://127.0.0.1:9502", $errno, $errstr, 1);
 if (!$fp) {
 echo "$errstr ($errno)\n";
 } else {
 stream_set_timeout($fp, 5);
 for ($n = 100; $n--;) {
 fwrite($fp, tcp_pack("Hello Swoole Server #{$n}!"));
 $data = fread($fp, tcp_length(fread($fp, 2)));
 assert($data === "Hello Swoole Client #{$n}!");
 }
 fclose($fp);
 }
 });
}
// udp server & client with 12.8k requests in single process
go(function () {
 $socket = new Swoole\Coroutine\Socket(AF_INET, SOCK_DGRAM, 0);
 $socket->bind('127.0.0.1', 9503);
 $client_map = [];
 for ($c = 128; $c--;) {
 for ($n = 0; $n < 100; $n++) {
 $recv = $socket->recvfrom($peer);
 $client_uid = "{$peer['address']}:{$peer['port']}";
 $id = $client_map[$client_uid] = ($client_map[$client_uid] ?? -1) + 1;
 assert($recv === "Client: Hello #{$id}!");
 $socket->sendto($peer['address'], $peer['port'], "Server: Hello #{$id}!");
 }
 }
 $socket->close();
});
for ($c = 128; $c--;) {
 go(function () {
 $fp = stream_socket_client("udp://127.0.0.1:9503", $errno, $errstr, 1);
 if (!$fp) {
 echo "$errstr ($errno)\n";
 } else {
 for ($n = 0; $n < 100; $n++) {
 fwrite($fp, "Client: Hello #{$n}!");
 $recv = fread($fp, 1024);
 list($address, $port) = explode(':', (stream_socket_get_name($fp, true)));
 assert($address === '127.0.0.1' && (int)$port === 9503);
 assert($recv === "Server: Hello #{$n}!");
 }
 fclose($fp);
 }
 });
}
Swoole\Event::wait();
echo 'use ' . (microtime(true) - $s) . ' s';

?? 安装

和任何开源项目一样, Swoole总是在最新的发行版提供最可靠的稳定性和最强的功能, 请尽量保证你使用的是最新版本

1. 直接使用Swoole官方的二进制包 (初学者 + 开发环境)

访问我们官网的下载页面

编译需求

  • Linux, OS X 系统 或 CygWin, WSL
  • PHP 7.0.0 或以上版本 (版本越高性能越好)
  • GCC 4.8 及以上

2. 使用PHP官方的PECL工具安装 (初学者)

pecl install swoole

3. 从源码编译安装 (推荐)

非内核开发研究之用途, 请下载发布版本的源码编译

cd swoole-src && \
phpize && \
./configure && \
make && sudo make install

启用扩展

编译安装到系统成功后, 需要在php.ini中加入一行extension=swoole.so来启用Swoole扩展

额外编译参数

使用例子: ./configure --enable-openssl --enable-sockets

  • --enable-openssl 或 --with-openssl-dir=DIR
  • --enable-sockets
  • --enable-http2
  • --enable-mysqlnd (需要 mysqlnd, 只是为了支持mysql->escape方法)

升级

?? 如果你要从源码升级, 别忘记在源码目录执行 make clean

  1. pecl upgrade swoole
  2. git pull && cd swoole-src && make clean && make && sudo make install
  3. 如果你改变了PHP版本, 请重新执行 phpize clean && phpize后重新编译

框架 & 组件

  • Hyperf 是一个高性能、高灵活性的协程框架,存在丰富的可能性,如实现分布式中间件,微服务架构等
  • Swoft 是一个现代化的面向切面的高性能协程全栈组件化框架
  • Easyswoole 是一个极简的高性能的框架,让代码开发就好像写echo "hello world"一样简单
  • Saber 是一个人性化的高性能HTTP客户端组件,几乎拥有一切你可以想象的强大功能

私信回复" swoole-src"获取链接地址,喜欢的点个关注,一起学习探讨新技术。

相关推荐

React 开发翻车现场!这 6 个救命技巧,90% 工程师居然现在才知道

前端圈最近都在卷React18新特性,可咱开发时踩的坑却一个比一个离谱!组件卡死、状态乱套、路由错乱...别担心!今天分享6个超实用的React实战技巧,让你轻松拿捏开发难题,代码直接...

Web前端:React JS越来越受欢迎,它的主要优点为什么要使用它?

  ReactJS是一个开源JavaScript库,用于为单页应用程序构建用户界面,它还为不同的移动应用程序提供视图层,并创建可重用的UI组件。  我们可以在Web应用程序的数据中创建特定的更改,而...

性能焦虑!前端人必看!5 个 React 组件优化神技! 颠覆你的认知!

在前端开发的赛道上,性能优化就像一场永不停歇的马拉松。作为前端工程师,你是否常常为React组件的性能问题头疼不已?页面加载缓慢、组件频繁重渲染,这些痛点分分钟让开发进度受阻。别担心!今天就来分享...

React 实战必学!99% 工程师踩过的 5 大坑,3 招教你轻松破解

前端开发的小伙伴们,咱就是说,React现在可是前端界的“顶流明星”,热度一直居高不下!但用它开发项目的时候,是不是总有那么些瞬间,让你怀疑人生,对着屏幕疯狂抓头发?别慌!今天就给大家分享几个超实...

惬意!午间一道 React 题,轻松拿捏前端面试小技巧

忙碌了一上午,眼睛酸涩、脑子发懵?别急着刷短视频“放空”,不如花几分钟和我一起“品尝”一道React面试题小甜点!就像在阳光洒满窗台的午后,泡一杯热茶,惬意又能悄悄涨知识,何乐而不为?最近,...

一起深入盘点 2025 年 React 发展的 10个趋势?

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发!1.React服务器组件React服务...

前端掉坑血泪史!4 个 React 性能优化绝招让页面秒开

在前端圈子里摸爬滚打这么多年,我发现React开发时踩坑的经历大家都大同小异。页面加载慢、组件频繁重渲染、状态管理混乱……这些痛点,相信不少前端工程师都感同身受。别愁!今天就给大家分享4个超...

前端人崩溃瞬间!5 招 React 实战技巧让项目起死回生

有没有在写React项目时,遇到页面卡顿到怀疑人生、数据更新不及时、代码逻辑混乱到无从下手的情况?别慌!作为摸爬滚打多年的前端老炮,今天就把5个救命级的React实战技巧倾囊相授,帮你轻松...

8.3K star!React Bits,让你拥有全网几乎所有动画效果

前端开源项目101专栏:一个能让你更快接触到高质量开源项目的地方。我会探索分享精选101个高质量的开源项目。这是系列的第7篇文章,分享一套拥有计划全网所有动画效果,且创意最丰富的动画React组...

开始学习React - 概览和演示教程

#头条创作挑战赛#本文同步本人掘金平台的原创翻译:https://juejin.cn/post/6844903823085944846当我刚开始学习JavaScript的时候,我就听说了React,但...

阿里AI工具Web Dev上线!一句话生成React网页

5月11日,阿里巴巴推出全新AI工具“WebDev”,支持用户通过一句话指令生成网页应用。该工具集成HTML、CSS、JavaScript三大前端核心技术,并统一采用React框架实现,可在数秒内创...

JS流行框架/库排名Top100,看看你熟知的Js排第几

权威的JavaScript趋势榜stats.js.org每15分钟根据github上的stars和forks总数实时汇总出JavaScript开源项目的流行度排名,一起来看看你所熟知的项目排名第几...

新手如何搭建个人网站

ElementUl是饿了么前端团队推出的桌面端UI框架,具有是简洁、直观、强悍和低学习成本等优势,非常适合初学者使用。因此,本次项目使用ElementUI框架来完成个人博客的主体开发,欢迎大家讨论...

站在巨人肩膀上的 .NET 通用权限开发框架:Admin.NET

站在巨人肩膀上的.NET通用权限开发框架Admin.NET是一个面向.NET程序员的低代码平台,java平台类似的框架有ruoyi,芋道,JeelowCode等。这类框架普遍采用前后端分离的开发技...

Python+selenium自动化之判定元素是否存在

在测试过程中,我碰到过这类的问题,使用find_element却找不到某个元素而产生异常,这就需要在操作某个元素之前判定该元素是否存在,而selenium中没有判定元素是否存在的方法,或者判定相同的元...

取消回复欢迎 发表评论: