require_once __DIR__ . '/vendor/autoload.php';
use Clue\React\Redis\Factory;
use Clue\React\Redis\Client;
use Workerman\Worker;
$worker = new Worker('text://0.0.0.0:6161');
// 进程启动时
$worker->onWorkerStart = function() {
global $factory;
$loop = Worker::getEventLoop();
$factory = new Factory($loop);
};
$worker->onMessage = function($connection, $data) {
global $factory;
$factory->createClient('localhost:6379')->then(function (Client $client) use ($connection) {
$client->set('greeting', 'Hello world');
$client->append('greeting', '!');
$client->get('greeting')->then(function ($greeting) use ($connection){
// Hello world!
echo $greeting . PHP_EOL;
$connection->send($greeting);
});
$client->incr('invocation')->then(function ($n) use ($connection){
echo 'This is invocation #' . $n . PHP_EOL;
$connection->send($n);
});
});
};
Worker::runAll();
有看到官方给出的异步redis例子中是在onMessage中$factory->createClient('localhost:6379')->then()
疑问:每次来一条消息都要去创建一个连接,异步查询,并且用完就关闭该连接是否存在浪费资源? 请问推荐的最佳实践是怎样的? 是否将这个连接进行共用?
仅仅是个使用示例。
如果能复用链接当然最好了。
不过对于绝大多数业务来说,每次请求创建销毁redis链接的消耗可以忽略不记。