简体   繁体   中英

Async transactions with PHP and mySQL

When a certain action happens on the site (built in PHP and MySQL) I would like few asynchronous things to happen on the site.

For example, when a user answers a question, uploads document, I want few asynchronous things to happen in the background such as: 1.update user's score 2. Post a message on Facebook wall 3.track users actions.

What PHP, JavaScript and MySQL technologies are best for achieving this? Please help.

I want something that MySQL triggers but wanted to happen asynchronously.

The only two options I can think of are a messaging queue, and async ajax.

The first option works by putting jobs into a database, then a scheduled php program will loop through every job in the database and run them.

The second is just calling a php program using ajax.

For the first option look at something like: http://alanstorm.com/simple_php_job_queue
For the second look at jquery, and its ajax options: http://api.jquery.com/jQuery.ajax/

The best option is to call three separate PHP scripts using exec and passing the output to null, like below.

exec("/usr/bin/php somescript.php >> some_log_file.log 2>&1 &");

Doing the same exec on three scripts for your three functions will execute, all three things concurrently/asynchronously. This is what your after.

If you add jobs to a job queue and then have a cron clear that queue, your not really doing it asynchronously. Your still doing things one by one, in a synchronous blocking fashion - although the user is not waiting for these things to happen. There might be a delay in the queue being cleared as well if your site has high traffic, you won't get the same delay with exec. Since the script will be executed immediately and concurrently to the initial request.

Side Note: This is why Node.js is becoming so popular it's built on JavaScript which is designed for this kind of development approach. Asynchronous and event driven.

Use the swoole extension. https://github.com/matyhtf/swoole

asyc mysql example:

$db = new mysqli;
$db->connect('127.0.0.1', 'root', 'root', 'test');
$db->query("show tables", MYSQLI_ASYNC);
swoole_event_add(swoole_get_mysqli_sock($db), function($__db_sock) {
    global $db;
    $res = $db->reap_async_query();
    var_dump($res->fetch_all(MYSQLI_ASSOC));
    exit;
});

您可以使用消息队列服务器。

您也可以使用php系统调用在后台运行另一个程序: http : //php.net/manual/en/function.system.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM