首页
导航
博客
电子书
算法
众创
代码
随贴
关于我们
您好,欢迎来到码863代码分享网! 请
[登录]
/
[注册]
搜 索
swoole,redis进程池
编辑
代码正文
双击正文可选择全部
1[代码][php]
尝试一下
<?php $redis=new Redis; $redis->pconnect('127.0.0.1', 6379); $redis->del('set'); $pool = new RedisPool(); //创建websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server("0.0.0.0", 9502); //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request)use($pool) { $redis = $pool->get(); var_dump($request->fd, $request->get, $request->server); $redis->sadd('set',$request->fd); $ws->push($request->fd, "服务器回复连接成功,redis保存连接".($redis->sismember('set',$request->fd)? '成功':'失败')); $pool->put($redis); }); //监听WebSocket消息事件 $ws->on('message', function ($ws, $frame) { echo "Message: {$frame->data}\n"; $ws->push($frame->fd, "server: {$frame->data}"); }); //监听WebSocket连接关闭事件 $ws->on('close', function ($ws, $fd)use($pool) { $redis = $pool->get(); $redis->srem('set',$fd); echo "client-{$fd} is closed\n"; $pool->put($redis); }); /*每隔2000ms触发一次*/ swoole_timer_tick(5000, function ($timer_id)use($pool) { $redis = $pool->get(); print_r($redis->smembers('set')); $pool->put($redis); echo $pool->get_count(); }); $ws->start(); class RedisPool { protected $available = true; protected $pool; public function __construct() { $this->pool = new SplQueue; } public function put($redis) { $this->pool->push($redis); } public function get_count() { return count($this->pool); } /** * @return bool|mixed|\Swoole\Coroutine\Redis */ public function get() { //有空闲连接且连接池处于可用状态 if ($this->available && count($this->pool) > 0) { return $this->pool->pop(); } //无空闲连接,创建新连接 $redis = new Swoole\Coroutine\Redis(); $res = $redis->connect('127.0.0.1', 6379); if ($res == false) { return false; } else { return $redis; } } public function destruct() { // 连接池销毁, 置不可用状态, 防止新的客户端进入常驻连接池, 导致服务器无法平滑退出 $this->available = false; while (!$this->pool->isEmpty()) { $this->pool->pop(); } } }
文明上网理性发言,请遵守新闻评论服务协议
0 条评论
发布评论
全部评论
最新
/
最热
暂无评论
加载更多
CopyRight 2002~2023 精通2100网 联系邮箱:qqtxt@163.com
版权所有:精通2100网
湘ICP备2023018646号-1
MYSQl共执行 3 个查询,用时 0.0018467903137207 秒,PHP脚本用时 0.003976 秒,占用内存 0.507 MB,Gzip 已启用