php异步干货

public function index(){
        $url = 'http://www.baidu.top/tp32/index.php/Home/Index/index2.html';
        $info = parse_url($url);
        $fp = fsockopen($info["host"],80,$errno,$errstr,30);
        $head = "POST " . $info['path'] . "?" . $info["query"] . " HTTP/1.0\r\n";
        $head .= "Host: " . $info['host'] . "\r\n";
        $head .= "Referer: http://" . $info['host'] . $info['path'] . "\r\n";
        $head .= "Content-type: application/x-www-form-urlencoded\r\n";
        $head .= "Content-Length: ". strlen(trim($query)) . "\r\n";
        $head .= "\r\n";
        $head  .= trim($query);
        $write = fputs($fp,$head);
        /*while(!feof($fp)){
            $line = fread($fp,4096);
            echo $line;
        }*/
        fclose($fp);
        var_dump(123);die;
    }

    public function index2(){
        sleep(5);
        $res = M('test3')->add(['title'=>mt_rand(11111,99999)]);
        var_dump($res);die;  
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP 中实现异步写入数据库可以使用以下两种方法: 1. 使用 Swoole 扩展 Swoole 是一个高性能的异步网络通信框架,可以用来实现异步写入数据库。以下是一个简单的示例代码: ```php $server = new swoole_server("127.0.0.1", 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP); $server->on('receive', function ($serv, $fd, $from_id, $data) { $serv->send($fd, "hello\n"); $serv->after(1000, function () use ($fd) { $dbh = new PDO('mysql:host=localhost;dbname=test', 'root', 'password'); $dbh->exec("INSERT INTO `test` (`name`) VALUES ('test')"); $dbh = null; $serv->send($fd, "world\n"); }); }); $server->start(); ``` 2. 使用 MySQLi 的异步 API MySQLi 是 PHP 的一个扩展库,它提供了异步 API,可以用来实现异步写入数据库。以下是一个简单的示例代码: ```php $mysqli = new mysqli("127.0.0.1", "root", "password", "test", 3306, null, MYSQLI_ASYNC); $mysqli->query("INSERT INTO `test` (`name`) VALUES ('test')", MYSQLI_ASYNC); $links = [$mysqli]; $wait_for = null; $wait_timeout_sec = 1; $wait_timeout_usec = 0; do { $result = mysqli_poll($links, $wait_for, $wait_timeout_sec, $wait_timeout_usec); if ($result === false) { echo "Error: " . mysqli_error($mysqli); break; } elseif ($result > 0) { $result = $mysqli->reap_async_query(); var_dump($result); break; } } while (true); ``` 需要注意的是,使用 MySQLi 异步 API 需要开启 MySQLi 的异步模式,而且只有在 PHP 编译时开启了 mysqli 模块的异步支持才能使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值