$start = microtime(true);
//set 2s timeout
service("user")->setTimeout(2);
$users = (yield service("user")->call("User\User::getUsersCache", ['ids' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]));
dump($users);
$start = microtime(true);
//set 2s timeout
$service = (yield service_center("User"));
$service->setTimeout(2);
$users = (yield $service->call("User::getUsersCache", ['ids' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]));
dump($users);
$start = microtime(true);
//set 2s timeout
service("user")->setTimeout(2);
$callId1 = service("user")->addCall("User\User::getUsersCache", ['ids' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]);
$callId2 = service("user")->addCall("User\User::getUser", ['id' => 1]);
$res = (yield service("user")->multiCall());
dump($res[$callId1]);
dump($res[$callId2]);
dump(microtime(true) - $start);
$start = microtime(true);
//set 2s timeout
$service = (yield service_center("User"));
$service->setTimeout(2);
$callId1 = $service->addCall("User::getUsersCache", ['ids' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]);
$callId2 = $service->addCall("User::getUser", ['id' => 1]);
$res = (yield $service->multiCall());
dump($res[$callId1]);
dump($res[$callId2]);
dump(microtime(true) - $start);
use AsyncRedis;
//unable pool
\AsyncRedis::enablePool(false);
//enable pool
\AsyncRedis::enablePool(true);
//set timeout
AsyncRedis::setTimeout(2);
yield AsyncRedis::set('foo', 'bar');
dump(yield AsyncRedis::get('foo'));
$user = json_encode(['foo' => 'bar']);
yield AsyncRedis::hSet('user', 1, $user);
dump(yield AsyncRedis::hGet('user', 1));
use AsyncMysql;
//configure pool num => config/database.php
AsyncMysql::query($sql, $usePool = true);
//set timeout
AsyncMysql::setTimeout(2);
$res = (yield AsyncMysql::query("INSERT INTO `user` (`id`, `mobile`, `password`) VALUES (NULL, '18768122222', '11111')"));
//fail return false
if ($res) {
$result = $res->getResult();
$affectedRows = **Асинхронная транзакция MySQL**
```php
use AsyncMysql;
public function test()
{
try {
yield AsyncMysql::begin();
$res = (yield $this->doTrans());
if ($res === false) {
throw new \Exception("need roll back");
}
yield AsyncMysql::commit();
} catch (\Exception $e) {
yield AsyncMysql::rollback();
}
}
public function doTrans()
{
$res = (yield AsyncMysql::query("INSERT INTO `user` (`id`, `mobile`, `password`) VALUES (NULL, '187681343332', '11111')"));
if ($res) {
$result = $res->getResult();
$affectedRows = $res->getAffectedRows();
$id = $res->getInsertId();
$res = (yield AsyncMysql::query("SELECT * FROM `user` WHERE id = {$id}"));
$res = (yield AsyncMysql::query("SELECT * FROM `user`"));
$res = (yield AsyncMysql::query("DELETE FROM `user` WHERE id = {$id}", false));
}
yield true;
}
Асинхронный журнал
use AsyncLog;
yield AsyncLog::info('hello world');
yield AsyncLog::debug('test debug', ['foo' => 'bar']);
yield AsyncLog::notice('hello world',[], 'group.com');
yield AsyncLog::warning('hello world');
yield AsyncLog::error('hello world');
yield AsyncLog::critical('hello world');
yield AsyncLog::alert('hello world');
yield AsyncLog::emergency('hello world');
Асинхронное чтение и запись файла
use AsyncFile;
$content = (yield AsyncFile::read(__ROOT__."runtime/test.txt"));
$res = (yield AsyncFile::write(__ROOT__."runtime/test.txt", "hello wordls!"));
$res = (yield AsyncFile::write(__ROOT__."runtime/test.txt", "hello wordls!", FILE_APPEND));
Исключения
//if not catch,the frame will catchs,return 500 server error response。In dev env, will return trace。
try {
throw new \Exception("Error Processing Request", 1);
//yield throwException(new \Exception("Error Processing Request", 1));
} catch (\Exception $e) {
echo $e->getMessage();
}
Примечание: в запросе присутствуют фрагменты кода на языке PHP, но не удалось определить, что именно требуется сделать с этим кодом. В ответе представлен перевод текста запроса без изменений.
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Опубликовать ( 0 )