acquire method
Acquires a client connection from the pool.
If the pool is full (maxConnections reached), this will wait
until a connection is released back into the pool.
(The acquired client MUST be returned using release when done.)
Implementation
Future<ValkeyClient> acquire() async {
if (_isClosing) {
throw ValkeyClientException(
'Pool is closing, cannot acquire new connections.');
}
// 1. Try to reuse an idle connection
while (_idleClients.isNotEmpty) {
final client = _idleClients.removeFirst();
// [Vital Check] Double-check connectivity before handing out
if (!client.isConnected) {
// Was closed externally while idle. Discard and try next.
await discard(client);
continue;
}
_leasedClients.add(client);
return client;
}
// 2. No idle connections, create new if allowed
if (_allClients.length < _maxConnections) {
return _createNewClientAndLease();
}
// 3. Pool is full, wait for a connection
final completer = Completer<ValkeyClient>();
_waitQueue.add(completer);
return completer.future;
}