首页 国际新闻正文

萧蔷,异步、并行、高性能网络通信引擎 swoole-src,唐朝

Swoole杨彩熙是一个为PHP用C和C++编写的根据事情的高功用异步萧蔷,异步、并行、高功用网络通讯引擎 swoole-src,唐朝&协程并行网络通讯引擎

✨事情驱动

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\Http萧蔷,异步、并行、高功用网络通讯引擎 swoole-src,唐朝2\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(funct赵乐天ion () 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\Corou吴开信tine\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萧蔷,异步、并行、高功用网络通讯引擎 swoole-src,唐朝, 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-src,唐朝

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');
$channe驭奴l->push(['A', json_encode($addr_info, JSON_PRETTY_PRINT)]);
});
go(fu白应鑫nction () 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 萧蔷,异步、并行、高功用网络通讯引擎 swoole-src,唐朝date
$shjmptchannel->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('萧蔷,异步、并行、高功用网络通讯引擎 swoole-src,唐朝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($addres本道s === '127.0.0.1' && (int)$port === 9503);
assert($recv === "Server: Hello #{$n}!");
}
fclose($fp);
}
});
}
Swoole\Event::wait();
ech恒源不夜城o '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 是一个现代化的面向切面的高性萧蔷,异步、并行、高功用网络通讯引擎 swoole-src,唐朝能协程全栈组件化结构
  • Easyswoole 是一个极简的高功用的结构,让代码开发就好像写echo "hello world"相同简略
  • Saber 是一个人性化的高功用HTTP客户端组件,简直具有全部你能够幻想的强壮功用

私信回复" swoole-src"获取链接地址,喜爱的点个重视,一同学习讨论新技术。

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。