AsyncMysqlClient::setPoolsConnectionLimit

Sets the connection limit of all connection pools using this client.

Description

public static function setPoolsConnectionLimit(
  int $limit,
): void

Sets the connection limit of all connection pools using this client.

Use this function to toggle the number of allowed async connections on the pools connecting to MySQL with this current client. For example, if you set the limit to 2, and you try a third connection on the same pool, an AsyncMysqlConnectException exception will be thrown.

Parameters

  • int $limit - The limit for all pools.

Examples

You can use AsyncMysqlClient::setPoolsConnectionLimit() to toggle the number of allowed async connections on the client. In this example, we are setting the number of allowed pool connections to be 2, but trying to do 3 connections, and that ends up giving an exception.

<?hh

namespace Hack\UserDocumentation\API\Examples\AsyncMysql\Client\setPCL;

use \Hack\UserDocumentation\API\Examples\AsyncMysql\ConnectionInfo as CI;

function set_connection_pool(): \AsyncMysqlConnectionPool {
  return new \AsyncMysqlConnectionPool(array());
}

async function connect_with_pool(\AsyncMysqlConnectionPool $pool):
  Awaitable<\AsyncMysqlConnection> {
  return await $pool->connect(
    CI::$host,
    CI::$port,
    CI::$db,
    CI::$user,
    CI::$passwd
  );
}

function get_stats(\AsyncMysqlConnectionPool $pool): array<mixed> {
  return $pool->getPoolStats();
}

function run_it(): void {
  \AsyncMysqlClient::setPoolsConnectionLimit(2); // limit two connections
  $pool = set_connection_pool();
  $conn_awaitables = Vector {};
  try {
    // One of these 3 connections here will throw the exception when we join
    $conn_awaitables[] = connect_with_pool($pool);
    $conn_awaitables[] = connect_with_pool($pool);
    $conn_awaitables[] = connect_with_pool($pool);
    $conns = \HH\Asio\join(\HH\Asio\v($conn_awaitables));
  } catch (\AsyncMysqlConnectException $ex) {
    var_dump(get_stats($pool));
  }
}

run_it();
Output
array(5) {
  ["created_pool_connections"]=>
  int(2)
  ["destroyed_pool_connections"]=>
  int(0)
  ["connections_requested"]=>
  int(3)
  ["pool_hits"]=>
  int(0)
  ["pool_misses"]=>
  int(3)
}