目录
官网文档
安装
命令行
服务启动
热更新
websocket
聊天室room实现
事件订阅
Task任务投递
高性能共享内存 Table
RPC
服务器端
接口定义app/rpc/interfaces/UserInterface.php
实现接口app/rpc/services/UserService.php
注册rpc服务config/swoole.php
客户端
定时任务
首页 php框架 ThinkPHP 分享一个think-swoole实战案例【详细演示】

分享一个think-swoole实战案例【详细演示】

Jul 23, 2021 pm 03:08 PM
swoole

官网文档

thinkphp6文档
https://www.kancloud.cn/manual/thinkphp6_0/1037479 
swoole文档
https://wiki.swoole.com/#/
think-swoole文档
https://www.kancloud.cn/manual/thinkphp6_0/1359700
登录后复制

安装

composer require topthink/think-swoole
登录后复制

命令行

php think swoole [start|stop|reload|restart]
登录后复制

服务启动

当你在命令行php think swoole下执行完成之后就会启动一个HTTP Server,可以直接访问当前的应用【推荐教程:thinkphp

'server'     => [
    'host'      => env('SWOOLE_HOST', '0.0.0.0'), // 监听地址
    'port'      => env('SWOOLE_PORT', 9501), // 监听端口
    'mode'      => SWOOLE_PROCESS, // 运行模式 默认为SWOOLE_PROCESS
    'sock_type' => SWOOLE_SOCK_TCP, // sock type 默认为SWOOLE_SOCK_TCP
    'options'   => [
        // 服务启动后,进程ID存放文件
        'pid_file'              => runtime_path() . 'swoole.pid',
        // swoole 的日志文件
        'log_file'              => runtime_path() . 'swoole.log',
        // 守护进程模式设置 true 后台运行
        'daemonize'             => false,
        // 设置启动的reactor线程数
        'reactor_num'           => swoole_cpu_num(),
        // 设置启动的worker进程数
        'worker_num'            => swoole_cpu_num(),
        //配置Task进程的数量
        'task_worker_num'       => swoole_cpu_num(),
        //开启静态文件请求处理,需配合document_root
        'enable_static_handler' => true,
        //静态文件根目录
        'document_root'         => root_path('public'),
        // 设置最大数据包尺寸,单位字节
        'package_max_length'    => 20 * 1024 * 1024,
        //配置发送输出缓冲区内存尺寸
        'buffer_output_size'    => 10 * 1024 * 1024,
        //设置客户端连接最大允许占用的内存数量
        'socket_buffer_size'    => 128 * 1024 * 1024,
    ],
],
登录后复制

热更新

swoole服务器运行过程中php文件是常驻内存运行,这样就可以避免重复的读取磁盘,重复的解释编译php,以便达到最高的性能,所以修改代码需要重启服务

think-swoole扩展提供热更新功能,在检测相关文件有更新会自动重启,不在需要手动完成重启,方便开发调试

生产环境下不建议开始文件监控,性能损耗,正常情况下你所修改的文件需要确认无误才能进行更新部署

.env里面设置APP_DEBUG = true会默认开启热更新

'hot_update' => [
    'enable'  => env('APP_DEBUG', false),
    'name'    => ['*.php'],
    'include' => [app_path()],
    'exclude' => [],
],
登录后复制

参数说明

参数说明
enable是否开启热更新
name监听哪些类型的文件变动
include监听哪些目录下的文件变动
exclude排除目录

websocket

先来一个官方的例子

$server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
$server->on('open', function (Swoole\WebSocket\Server $server, $request) {
    echo "server: handshake success with fd{$request->fd}\n";
});
$server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data}\n";
    $server->push($frame->fd, "this is server");
});
$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});
$server->start();
登录后复制

开启think-swoole的websocket功能 \config\swoole.php

'websocket'  => [
    'enable'        => true,
],
登录后复制

创建三个事件

php think make:listener SwWsConnect
php think make:listener SwWsClose
php think make:listener SwWsMessage
登录后复制

然后将这三个事件写到到事件监听中,分别有以下2中文件可以修改方式,注意二选一

thinkphp6自带的事件绑定app\event.php

    'listen'    => [
        ........
        // 监听链接
        'swoole.websocket.Connect' => [
            \app\listener\SwWsConnect::class
        ],
        //关闭连接
        'swoole.websocket.Close' => [
            \app\listener\SwWsClose::class
        ],
        //发送消息场景
        'swoole.websocket.Message' => [
            \app\listener\SwWsMessage::class
        ]
    ],
登录后复制

think-swoole事件绑定config\swoole.php

'listen'        => [
    'connect'=>\app\listener\SwWsConnect::class,
    'close'=>\app\listener\SwWsClose::class,
    'message'=> \app\listener\SwWsMessage::class
],
登录后复制
怎么选择是保存在config\swoole.php还是app\event.php配置中呢?

首先我们 我们确定一下我们这个项目中存在有几个实时通讯,

如果只是存在一个实时通讯 个人建议 保存在config\swoole.php

如果是存在多个实时通讯,就保存在app\event.php

key值 必须是swoole.websocket.事件名称 例如 swoole.websocket.Message

开始写事件中中方法

连接事件app\listener\SwWsConnect.php

public function handle($event, \think\swoole\websocket $ws)
{
    // 获取当前发送者的fd
    $fd = $ws->getSender();
    echo "server: handshake success with fd{$fd}\n";
}
登录后复制

关闭事件app\listener\SwWsClose.php

public function handle($event, \think\swoole\websocket $ws)
{
    $fd = $ws->getSender();
    echo "client {$fd} closed\n";
}
登录后复制

message事件app\listener\SwWsMessage.php

public function handle($event, \think\swoole\websocket $ws)
{
    $fd = $ws->getSender();
    $data = json_encode($event);
    echo "receive from {$fd}:{$data}\n";
    $ws->emit("this is server", $fd);
}
登录后复制

启动php think swoole进行测试

think-swoole中的websocket方法总结

//给自己发消息
$ws->emit("this is server", $ws->getSender());
//给指定一个fd发消息
$ws->to($to)->emit("messagecallback",$data);
//给指定多个人发消息
$ws->to([1,2,3])->emit("messagecallback",$data);
//发送给所有的(不包含自己)
$ws->broadcast()->emit("messagecallback",$data);
//模拟formfd 给tofd 发送消息
$ws->setSender($formfd)->to($tofd)->emit("messagecallback",$data);
登录后复制
注意:在多个实时通讯场景下使用 emit

第一个参数传入 传入 事件名称callback 例如 messagecallback

如果你发现你think-swoole中有些没有swoole中的方法可以这么干

$sw = app('swoole.server');
$sw = app("think\swoole\Manager")->getServer();
//以上二选一

$es = $sw->isEstablished($fd); //检查连接是否为有效的WebSocket客户端连接
var_dump($es);
登录后复制

聊天室room实现

前端文件参考 html\room.htmlhtml\room-socket-io.html

php think make:listener SwRoomJoin
php think make:listener SwRoomLeave
php think make:listener SwRoomMessage
登录后复制

事件绑定

// 加入房间
'swoole.websocket.RoomJoin' => [
    \app\listener\SwRoomJoin::class
],
// 离开房间
'swoole.websocket.Roomleave' => [
    \app\listener\SwRoomLeave::class
],
// 在房间发消息
'swoole.websocket.RoomMessage' => [
    \app\listener\SwRoomMessage::class
]
登录后复制

加入房间逻辑

public function handle($event, \think\swoole\websocket $ws, \think\swoole\websocket\room $room)
{
    $fd = $ws->getSender();
    //客户端假如定的room
    $roomid = $event['room'];
    //获取指定房间下有哪些客户端
    $roomfds = $room->getClients($roomid);
    // 判断这个房间有没有自己 如果有自己就不需要再次发送通知
    if (in_array($fd, $roomfds)) {
        $ws->to($roomfds)->emit("roomjoincallback", "房间{$roomid}已加入");
        return;
    }
    //加入房间
    $ws->join($roomid);
    $ws->to($roomfds)->emit("roomjoincallback", "{$fd}加入房间{$roomid}成功");
}
登录后复制

离开房间逻辑

public function handle($event, \think\swoole\websocket $ws, \think\swoole\websocket\Room $room)
{
    $roomid = $event['room'];
    $fd = $ws->getSender();
    $roomfds = $room->getClients($roomid);
    if (!in_array($fd, $roomfds)) {
        $ws->emit("roomleavecallback", "{$fd}不在{$roomid}房间内,怎么离开~");
        return;
    }
    //离开房间
    $ws->leave($roomid);
    //获取当前客户端加入了哪些客户端
    $rooms = $room->getRooms($fd);
    $ws->to($roomfds)->emit("roomleavecallback", "{$fd}已离开了~~");
}
登录后复制

在房间发布聊天逻辑

    public function handle($event, \think\swoole\websocket $ws, \think\swoole\websocket\room $room)
    {
        //
        $roomid = $event['room'];
        $text = $event['text'];
        $fd = $ws->getSender();
        $roomfds = $room->getClients($roomid);
        if (!in_array($fd, $roomfds)) {
            $ws->emit("roommessagecallback", "{$fd}不在{$roomid}房间内,无法进入发布聊天~");
            return;
        }
        $ws->to($roomfds)->emit("roommessagecallback",  $text);
    }
登录后复制

事件订阅

php think make:listener SwSubscribe
登录后复制

applistenerSwSubscribe.php

<?php
declare (strict_types = 1);

namespace app\listener;

class SwSubscribe
{
    protected $ws = null;

    // public function __construct()
    // {
    //     $this->ws = app(&#39;think\swoole\Websocket&#39;);
    // }

    public function __construct(\think\Container $c)
    {
        $this->ws = $c->make(\think\swoole\Websocket::class);
    }
    
    public function onConnect()
    {
        $fd = $this->ws->getSender();
        echo "server: handshake success with fd{$fd}\n";
    }
    public function onClose()
    {
        $fd = $this->ws->getSender();
        echo "client {$fd} closed\n";
    }
    public function onMessage($event)
    {
        $fd = $this->ws->getSender();
        var_dump($event);
        echo "server: handshake success with fd{$fd}\n";
        $this->ws->emit("this is server", $fd);
    }
}
登录后复制

有点类似 将原生的swoole代码改成面向对象代码,生效方法 config\swoole.php中在subscribe 加入\app\listener\SwSubscribe::class

&#39;subscribe&#39;     => [
    \app\listener\SwSubscribe::class
],
登录后复制

app\event.php文件中的 swoole.websocket.Connect 相当于 app\listener\SwSubscribe.php文件中的onConnect函数。如果同时存在的存在的话,就会向客户端发送2次以上的消息

Task任务投递

https://wiki.swoole.com/#/start/start_task

生成事件

php think make:listener SwSendEmailTask
登录后复制

编写发送邮件方法app\listener\SwSendEmailTask.php

public function handle($event)
{
    var_dump($event);
    //
    echo "开发发送邮件".time();
    sleep(3);
    echo "结束发送邮件".time();
}
登录后复制

注册事件app\event.php

&#39;swoole.task&#39;=>[
    \app\listener\SwSendEmailTask::class
],
登录后复制

在控制器中投递任务

public function doRegister()
{
    $server = app(&#39;swoole.server&#39;);
    $server->task(\app\listener\SwSendEmailTask::class);
    return "注册成功";
}

public function doRegister(\think\swoole\Manager $manager)
{
    $server = $manager->getServer();
    $server->task(\app\listener\SwSendEmailTask::class);
    return "注册成功";
}
public function doRegister(\Swoole\Server $server)
{
    $server->task(\app\listener\SwSendEmailTask::class);
    return "注册成功";
}
登录后复制
三种获取\Swoole\Server,任意选其一

在swoole中还有一个事件叫finish,它的作用就是把异步任务的结果返回,在think-swool是这么处理的

定义一个发送邮件异步任务处理结果的事件

php think make:listener SwSendEmailFinish
登录后复制

注册事件app\event.php

&#39;swoole.finish&#39;=>[
    \app\listener\SwSendEmailFinish::class
],
登录后复制

在task任务中调用

public function handle($event)
{
    var_dump($event);
    //
    echo "开发发送邮件".time();
    sleep(3);
    echo "结束发送邮件".time();
    $event->finish(\app\listener\SwSendEmailFinish::class);
}
登录后复制

高性能共享内存 Table

https://wiki.swoole.com/#/mem...

先定结构在进行操作数据(原生swoole操作)

$table = new Swoole\Table(1024);
//创建表
$table->column("id", Swoole\Table::TYPE_INT);
$table->column("name", Swoole\Table::TYPE_STRING);
$table->column("money", Swoole\Table::TYPE_FLOAT);
$table->create();

//添加数据
$table->set("zq", [
    &#39;id&#39; => 1,
    &#39;name&#39; => "zhiqiang",
    &#39;money&#39; => 100,
]);
//获取一行数据
$table->get("zq");
// 修改数据
// 字段递增
$table->incr("zq","money",2);
//递减
$table->decr("zq","money",2);
// 返回 table 中存在的条目数。
$table->count();
//遍历table中的数据
foreach($table as $item){
    var_dump($item);
}
登录后复制

think-swoole中的操作

先对table表结构进行初始化config\swoole.php

    &#39;tables&#39;     => [
        &#39;user&#39;=>[
            &#39;size&#39;=>1024,
            &#39;columns&#39;=>[
                [
                    &#39;name&#39;=>&#39;id&#39;,
                    &#39;type&#39;=>\Swoole\Table::TYPE_INT
                ],
                [
                    &#39;name&#39;=>&#39;name&#39;,
                    &#39;type&#39;=>\Swoole\Table::TYPE_STRING,
                    &#39;size&#39;=>32
                ],
                [
                    &#39;name&#39;=>&#39;money&#39;,
                    &#39;type&#39;=>\Swoole\Table::TYPE_FLOAT
                ],

            ],
        ],
    ],
登录后复制

操作数据

$table =  app(&#39;swoole.table.user&#39;);
$table->set("zq", [
    &#39;id&#39; => 1,
    &#39;name&#39; => "zhiqiang",
    &#39;money&#39; => 100
]);
//获取一行数据
$table->get("zq");
// 修改数据
// 字段递增
$table->incr("zq", "money", 2);
//递减
$table->decr("zq", "money", 2);
// 返回 table 中存在的条目数。
$table->count();
//遍历table中的数据
foreach ($table as $item) {
var_dump($item);
}
// 检查 table 中是否存在某一个 key。
$table->exist(&#39;zq&#39;);
//获取实际占用内存尺寸,单位字节
$table->momorySize();
登录后复制

RPC

RPC(Remote Procedure Call):远程过程调用,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的思想。

详细介绍:https://developer.51cto.com/a...

  • 解决分布式系统中,服务之间的调用问题。
  • 远程调用时,要能够像本地调用一样方便,让调用者感知不到远程调用的逻辑。
  • 节点角色说明:
  • Server: 暴露服务的服务提供方
  • Client: 调用远程服务的服务消费方
  • Registry: 服务注册与发现的注册中心

think-swoole实现RPC功能

服务器端

接口定义app/rpc/interfaces/UserInterface.php

<?php
namespace app\rpc\interfaces;
interface UserInterface
{
    public function create();
    public function find(int $id);
}
登录后复制

实现接口app/rpc/services/UserService.php

<?php
namespace app\rpc\services;
use app\rpc\interfaces\UserInterface;
class UserService implements UserInterface
{
    public function create()
    {
        // TODO: Implement create() method.
        return "service create success";
    }
    public function find(int $id)
    {
        // TODO: Implement find() method.
        return $id. "查询数据遍历";
    }
}
登录后复制

注册rpc服务config/swoole.php

    &#39;rpc&#39;        => [
        &#39;server&#39; => [
            //开启rpc服务
            &#39;enable&#39;   => true,
            //rpc端口
            &#39;port&#39;     => 9000,
            &#39;services&#39; => [
                //注册服务
                \app\rpc\services\UserService::class
            ],
        ],
        // 如果填写也是可以调用其他服务端
        &#39;client&#39; => [
        ],
    ],
登录后复制

启动服务端

php think swoole start /  php think swoole:rpc
登录后复制

客户端

    &#39;rpc&#39;        => [
        &#39;server&#39; => [
        ],
        &#39;client&#39; => [
            &#39;tp6&#39;=>[
                //服务端的ip地址
                &#39;host&#39;=>&#39;127.0.0.1&#39;,
                //服务端对应的端口
                &#39;port&#39;=>&#39;9000&#39;
            ]
            // 更多服务端
        ],
    ],
登录后复制

运行php think rpc:interface生成RPC接口文件app\rpc.php

<?php
/**
 * This file is auto-generated.
 */
declare(strict_types=1);
namespace rpc\contract\tp6;
interface UserInterface
{
    public function create();
    public function find(int $id);
}
return [&#39;tp6&#39; => [&#39;rpc\contract\tp6\UserInterface&#39;]];
登录后复制

在控制器调用

    public function index(\rpc\contract\tp6\UserInterface $user)
    {
        //
        $user->find(1);
//        $user->create();
    }
登录后复制

定时任务

在think-swoole 2.0版本的时候还是支持自定义定时任务配置,详细参考https://github.com/top-think/think-swoole/tree/2.0

在3.0就不支持了,在这里介绍一个通用的命令行启动定时任务

php think make:command SwooleTimer
登录后复制

加载命令行config/console.php

&#39;commands&#39; => [
    &#39;swooletimer&#39;=>app\command\SwooleTimer::class
    ...........
],
登录后复制

书写命令脚本app/command/SwooleTimer.php

<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\input\Argument;


class SwooleTimer extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName(&#39;app\command\swooletimer&#39;)
            ->addArgument(&#39;action&#39;, Argument::OPTIONAL, "start | stop", &#39;start&#39;)
            ->setDescription(&#39;Swoole Timer for ThinkPHP&#39;);
    }


    public function handle()
    {
        $action = $this->input->getArgument(&#39;action&#39;);
        if (in_array($action, [&#39;start&#39;,&#39;stopall&#39;])) {
            $this->app->invokeMethod([$this, $action], [], true);
        } else {
            $this->output->writeln("<error>Invalid argument action:{$action}, Expected start</error>");
        }
    }

    /**
     * 启动定时任务 主要任务计划在这里书写
     */
    protected function start()
    {
        // https://wiki.swoole.com/#/timer
        $timer_id=swoole_timer_tick(2000,function (){
            echo "2s循环执行需要做的事情".time()."\n";
        });
        $this->output->writeln("Swoole Timer_id:{$timer_id} ");
    }

    /**
     * 清除所有的定时任务
     */
    protected  function stop(){
        swoole_timer_clear_all();
        $this->output->writeln("Swoole Timer  clear all ok");
    }
}
登录后复制

以上是分享一个think-swoole实战案例【详细演示】的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

swoole协程如何在laravel中使用 swoole协程如何在laravel中使用 Apr 09, 2024 pm 06:48 PM

Laravel 中使用 Swoole 协程可以并发处理大量请求,优势包括:并发处理:允许同时处理多个请求。高性能:基于 Linux epoll 事件机制,高效处理请求。低资源消耗:所需服务器资源更少。易于集成:与 Laravel 框架无缝集成,使用简单。

如何使用Swoole实现高性能的HTTP反向代理服务器 如何使用Swoole实现高性能的HTTP反向代理服务器 Nov 07, 2023 am 08:18 AM

如何使用Swoole实现高性能的HTTP反向代理服务器Swoole是一款基于PHP语言的高性能、异步、并发的网络通信框架。它提供了一系列的网络功能,可以用于实现HTTP服务器、WebSocket服务器等。在本文中,我们将介绍如何使用Swoole来实现一个高性能的HTTP反向代理服务器,并提供具体的代码示例。环境配置首先,我们需要在服务器上安装Swoole扩展

swoole和workerman哪个好 swoole和workerman哪个好 Apr 09, 2024 pm 07:00 PM

Swoole 和 Workerman 都是高性能 PHP 服务器框架。Swoole 以其异步处理、出色的性能和可扩展性而闻名,适用于需要处理大量并发请求和高吞吐量的项目。Workerman 提供了异步和同步模式的灵活性,具有直观的 API,更适合易用性和处理较低并发量的项目。

swoole_process 怎么让用户切换 swoole_process 怎么让用户切换 Apr 09, 2024 pm 06:21 PM

Swoole Process 中可以让用户切换,具体操作步骤为:创建进程;设置进程用户;启动进程。

swoole框架怎么重启服务 swoole框架怎么重启服务 Apr 09, 2024 pm 06:15 PM

要重启 Swoole 服务,请按照以下步骤操作:检查服务状态并获取 PID。使用 "kill -15 PID" 停止服务。使用启动服务的相同命令重新启动服务。

swoole和java哪个性能好 swoole和java哪个性能好 Apr 09, 2024 pm 07:03 PM

性能比较:吞吐量:Swoole 凭借协程机制,吞吐量更高。延迟:Swoole 的协程上下文切换开销更低,延迟更小。内存消耗:Swoole 的协程占用内存更少。易用性:Swoole 提供更易于使用的并发编程 API。

Swoole实战:如何使用协程进行并发任务处理 Swoole实战:如何使用协程进行并发任务处理 Nov 07, 2023 pm 02:55 PM

Swoole实战:如何使用协程进行并发任务处理引言在日常的开发中,我们常常会遇到需要同时处理多个任务的情况。传统的处理方式是使用多线程或多进程来实现并发处理,但这种方式在性能和资源消耗上存在一定的问题。而PHP作为一门脚本语言,通常无法直接使用多线程或多进程的方式来处理任务。然而,借助于Swoole协程库,我们可以使用协程来实现高性能的并发任务处理。本文将介

swoole协程是怎样调度的 swoole协程是怎样调度的 Apr 09, 2024 pm 07:06 PM

Swoole协程是一种轻量级并发库,允许开发者编写并发程序。Swoole协程调度机制基于协程模式和事件循环,使用协程栈管理协程执行,在协程让出控制权后挂起它们。事件循环处理IO和定时器事件,协程让出控制权时被挂起并返回事件循环。当事件发生时,Swoole从事件循环切换到挂起的协程,通过保存和加载协程状态完成切换。协程调度使用优先级机制,支持挂起、休眠和恢复操作以灵活控制协程执行。

See all articles