1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/cc_1234-Group-Co

Присоединиться к Gitlife
Откройте для себя и примите участие в публичных проектах с открытым исходным кодом с участием более 10 миллионов разработчиков. Приватные репозитории также полностью бесплатны :)
Присоединиться бесплатно
В этом репозитории не указан файл с открытой лицензией (LICENSE). При использовании обратитесь к конкретному описанию проекта и его зависимостям в коде.
Клонировать/Скачать
en.md 7.2 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
gitlife-traslator Отправлено 02.12.2024 11:43 b1fd262

Груп Ко

Введение

  • Использование корутин (генераторов). Написание асинхронного кода в синхронном стиле.
  • Использование Swoole.
  • Для API или HTTP-сервера.

* Асинхронный режим, корутины

* SOA

* AsyncLog, AsyncFile, AsyncMysql, AsyncRedis

* MysqlPool, RedisPool

* Транзакции Mysql

* Twig, Doctrine

* PhpUnit для тестирования

Требования
  • hiredis
  • redis
  • mysql
  • php5.6
  • swoole >=1.9.15 (компиляция с помощью ./configuire --enable-async-redis)
Установка
  • клонировать проект
  • запустить => composer install
  • создать каталог => runtime
  • настройка config/database.php
  • запуск http-сервера => php server.php
  • посетить http://localhost:9777/, работает!
Использование
  • запуск http-сервера => php server.php
  • перезагрузка htt pserver => php server.php -s reload
  • остановка http-сервера => php server.php -s stop
  • запуск одного сервиса => app/service user
  • перезагрузка одного сервиса => app/service user reload
  • закрытие одного сервиса => app/service user stop
Осторожно
    1. Нельзя установить параметр swoole => max_request.
    1. Проблемы с освобождением памяти, локальные статические переменные и глобальные переменные освобождаются.
Базовый сервис
  • AsyncMysql
  • AsyncRedis
  • AsyncService
  • AsyncLog
  • AsyncFile
  • Container
  • Controller
  • Config
  • Event
  • Route
  • Request
  • Response
  • StaticCache
  • Sync
    • Container
    • Console
    • FileCache
    • RedisCache
    • StaticCache
    • Log
    • Dao
    • Service
  • Test

Функции

Последовательный вызов
    
    $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);
    
Асинхронный redis (по умолчанию используется пул)
    
    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));
    
Асинхронный mysql (по умолчанию используется пул)
    
    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 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/cc_1234-Group-Co.git
git@api.gitlife.ru:oschina-mirror/cc_1234-Group-Co.git
oschina-mirror
cc_1234-Group-Co
cc_1234-Group-Co
master