业务需求示例:系统后台监听有新的商品订单,新消息等的通知,推送给所有登陆系统的用户。
逻辑:使用websocket建立连接,并设置定时器发送心跳保持连接不被断开。建立连接后,php端需要设置心跳时间,判断mysql业务表是否有新记录或者订单,如果有就推送消息给所有登陆系统用户,并更新该记录已推送。
### 1.composer先安装workerman组件
composer require topthink/think-worker`
### 2.配置
- worker配置 `config/worker_server.php`
// 扩展自身需要的配置
'protocol'???????=> 'websocket', // 协议 支持 tcp udp unix http websocket text
'host'???????????=> '0.0.0.0', // 监听地址
'port'???????????=> 2346, // 监听端口
'socket'?????????=> '', // 完整监听地址
'context'????????=> [], // socket 上下文选项
'worker_class'???=> 'app\work\Push', // 自定义Workerman服务类名 支持数组定义多个服务
- worker实现 `app/work/Push.php`
###?
<?php
namespace app\work;
use think\worker\Server;
use Workerman\Lib\Timer;
use think\facade\Db;
class Push extends Server
{
protected $socket = 'http://0.0.0.0:2346'; //端口自行修改
protected static $heartbeat_time = 55;
public function onWorkerStart($worker){
//查看是否有新的充值或提现订单,有就推送给所有用户
Timer::add(3, function()use($worker){
$time_now = time();
$hasNewDepositOrder = Db::name('deposit_order')->where('order_status',0)->where('is_push',0)->order('id desc')->count('id');
$system_listener = Db::name('system_listener')->cache(true)->order('id desc')->select()->toArray();
if($hasNewDepositOrder){
$depositOrderInfo = Db::name('deposit_order')->where('order_status',0)->where('is_push',0)->order('id desc')->find();
$data = ['creatTime'=>$depositOrderInfo['create_time'],'money'=>$depositOrderInfo['pay_amount'],'type'=>'deposit','system_listener'=>$system_listener];
foreach($worker->connections as $connection) {
if(empty($connection->lastMessageTime)){
$connection->lastMessageTime = $time_now;
}
if($time_now-$connection->lastMessageTime > self::$heartbeat_time){
$connection->close();
}
$connection->send(json_encode($data));
}
Db::name('deposit_order')->where('id',$depositOrderInfo['id'])->save(['is_push'=>1]);
}else{
foreach($worker->connections as $connection) {
if(empty($connection->lastMessageTime)){
$connection->lastMessageTime = $time_now;
continue;
}
if($time_now-$connection->lastMessageTime > self::$heartbeat_time){ //连接超时
$connection->close();
}
}
}
});
}
### 运行
`php think worker:server` reload|restart|stop|status
### ?websokcet实现?
<script>
let ws = new WebSocket("ws://127.0.0.1:2346")
ws.onopen = function() {??//绑定连接事件
????console.log("连接成功");
????//每30秒发送一次心跳
????setInterval(function(){
????????ws.send(JSON.stringify({'type':"peng"}));
????????console.log('发送心跳...');
????},30000)
};
ws.onmessage = function(evt) {//绑定收到消息事件
????data = JSON.parse(evt.data)
????console.log(data);
????//这里处理收到的消息, type类型有两种: connectin、deposit如果有deposit要提示有新的订单
};
ws.onclose = function(evt) { //绑定关闭或断开连接事件
console.log("连接已关闭");
};
</script>
|