- 使用Mysql
$db = new \Workerman\MySQL\Connection('host', 'port', 'user', 'password', 'db_name');
$db->query("SELECT ID,Sex FROM `Persons` WHERE sex='M' AND ID = 1");
$db->row("SELECT ID,Sex FROM `Persons` WHERE sex='M'"); 一行数据
$db->column("SELECT `ID` FROM `Persons` WHERE sex='M'"); 一列数据
$db->single("SELECT ID FROM `Persons` WHERE sex='M'"); 单个值
$db->beginTrans();事务开始
$db->commitTrans(); // or $db->rollBackTrans(); 回滚或提交
其余操作用使用 query即可
use \Workerman\Worker;
//use \Workerman\Lib\Timer;
require_once __DIR__ . '/Workerman/Autoloader.php';
require_once __DIR__ . '/Workerman/Mysql.php';
$worker = new Worker("http://0.0.0.0:2345");
// 开启多少个进程运行定时任务,注意业务是否在多进程有并发问题
$worker->count = 1;
$worker->onWorkerStart = function($worker)
{
global $db;
$db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'root', 'mysql', 'laravel');
};
$worker->onMessage = function($connection, $data)
{
// 通过全局变量获得db实例
global $db;
// 执行SQL
$all_tables = $db->query('select * from users');
$connection->send(dump($all_tables));
};
// 运行worker
Worker::runAll();
- 定时器加心跳
require_once __DIR__ . '/Workerman/Autoloader.php';
use Workerman\Worker;
use Workerman\Lib\Timer;
// 心跳间隔55秒
define('HEARTBEAT_TIME', 55);
$worker = new Worker('text://0.0.0.0:1234');
$worker->onMessage = function($connection, $msg) {
// 给connection临时设置一个lastMessageTime属性,用来记录上次收到消息的时间
$connection->lastMessageTime = time();
// 其它业务逻辑...
};
// 进程启动后设置一个每秒运行一次的定时器
$worker->onWorkerStart = function($worker) {
Timer::add(1, function()use($worker){
$time_now = time();
foreach($worker->connections as $connection) {
// 有可能该connection还没收到过消息,则lastMessageTime设置为当前时间
if (empty($connection->lastMessageTime)) {
$connection->lastMessageTime = $time_now;
continue;
}
// 上次通讯时间间隔大于心跳间隔,则认为客户端已经下线,关闭连接
if ($time_now - $connection->lastMessageTime > HEARTBEAT_TIME) {
$connection->close();
}
}
});
};
Worker::runAll();
- 定时任务处理队列
use \Workerman\Worker;
use \Workerman\Lib\Timer;
require_once __DIR__ . '/Workerman/Autoloader.php';
require_once __DIR__ . '/Workerman/Mysql.php';
$worker = new Worker();
// 开启多少个进程运行定时任务,注意业务是否在多进程有并发问题
$worker->count = 4;
$worker->onWorkerStart = function($worker)
{ global $db,$redis;
$db = new \Workerman\MySQL\Connection('127.0.0.1', '3306', 'root', 'mysql', 'laravel');
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
if($worker->id == 0)//只在第一个上边使用定时
{
Timer::add(5, function(){
global $redis;
while(true) {
$res = $redis->rpop("sendsms");
if ($res) {
$arr = unserialize($res);//取出队列
echo '取出成功'.date("Y-m-d H:i:s")."\n";
} else {
return;
}
}
});
}
};
// 运行worker
Worker::runAll();
作者:Yoby 创建时间:2020-07-23 20:14
更新时间:2024-12-05 13:26
更新时间:2024-12-05 13:26