其他分享
首页 > 其他分享> > workerman

workerman

作者:互联网

$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();

 

标签:__,worker,db,Workerman,connection,Worker,workerman
来源: https://blog.51cto.com/u_13481146/2820752