Swoole使用Redis连接池

<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
ini_set('memory_limit', '-1');
error_reporting(-1);
set_time_limit(0);
PHP_SAPI !== 'cli' && exit('脚本只能在命令行执行');

Swoole\Coroutine::set(['hook_flags' => SWOOLE_HOOK_ALL | SWOOLE_HOOK_CURL]); // 一键协程化

Swoole\Coroutine\run(function () {
    $server = new Swoole\Coroutine\Http\Server('localhost', 9502, false); // 创建HTTP服务器

    // 创建Redis配置对象
    $config = new Swoole\Database\RedisConfig();
    $config->withHost('localhost');
    $config->withPort(6379);
    $config->withAuth('**');
    $config->withDbIndex(0);
    $config->withTimeout(1);

    // 创建Redis连接池,并指定连接池中Redis实例数量为64个(缺省值也是64)
    // $pool = new Swoole\Database\RedisPool($config, 64);
    $pool = new Swoole\Database\RedisPool($config, 3); // 测试Redis连接池没有Redis实例(只取出不放回)

    // 处理任意请求
    $server->handle('/', function (Swoole\Http\Request $request, Swoole\Http\Response $response) use ($pool) {
        Swoole\Coroutine::create(static function () use ($request, $response, $pool): void {
            $method = $request->getMethod(); // 获取当前请求的请求方式
            ($method !== 'POST' && $method !== 'GET') && throw new Swoole\ExitException('Error');

            try {
                $redis = $pool->get(); // 从Redis连接池里获取一个Redis实例(连接失败会抛出异常)
            } catch (RedisException $e) {
                throw new Swoole\ExitException($e->getMessage());
            }

            // 将Redis实例放回Redis连接池
            defer(static function () use ($pool, $redis) {
                $pool->put($redis);
                echo 'Redis实例已放回Redis连接池' . PHP_EOL;
            });

            $redis->set('name', '张三');
            $redis->set('gender', '男');
            $redis->set('birth', 2003);

            $name = $redis->get('name');
            $gender = $redis->get('gender');
            $birth = $redis->get('birth');
            $html = "俺叫$name($gender),出生于{$birth}年。";

            $response->header('Content-Type', 'text/html; charset=utf-8');
            $response->end($html);
        });
    });

    $server->start(); // 启动HTTP服务器
});

Copyright © 2024 码农人生. All Rights Reserved