Laravel Aws Redis Error While Reading Line From the Server.
Predis
A flexible and feature-consummate Redis client for PHP 7.2 and newer.
ATTENTION: you are on the README file of an unstable co-operative of Predis specifically meant for the development of future releases. This means that the lawmaking on this co-operative is potentially unstable, and breaking change may happen without whatsoever prior notice. Do non utilise it in production environments or use it at your own risk!
Predis does not require any additional C extension by default, simply it can be optionally paired with phpiredis to lower the overhead of the serialization and parsing of the Redis RESP Protocol.
More than details about this project can be found on the oftentimes asked questions.
Main features
- Support for Redis from 2.0 to 6.0.
- Back up for clustering using customer-side sharding and pluggable keyspace distributors.
- Support for redis-cluster (Redis >= iii.0).
- Support for master-slave replication setups and redis-sentinel.
- Transparent key prefixing of keys using a customizable prefix strategy.
- Command pipelining on both single nodes and clusters (customer-side sharding only).
- Brainchild for Redis transactions (Redis >= 2.0) and CAS operations (Redis >= ii.ii).
- Abstraction for Lua scripting (Redis >= ii.6) and automatic switching between
EVALSHA
orEVAL
. - Abstraction for
Scan
,SSCAN
,ZSCAN
andHSCAN
(Redis >= 2.8) based on PHP iterators. - Connections are established lazily by the customer upon the get-go command and tin exist persisted.
- Connections tin be established via TCP/IP (as well TLS/SSL-encrypted) or UNIX domain sockets.
- Support for Webdis (requires both
ext-ringlet
andext-phpiredis
). - Support for custom connection classes for providing unlike network or protocol backends.
- Flexible system for defining custom commands and override the default ones.
How to install and use Predis
This library tin be plant on Packagist for an easier management of projects dependencies using Composer. Compressed athenaeum of each release are bachelor on GitHub.
Loading the library
Predis relies on the autoloading features of PHP to load its files when needed and complies with the PSR-4 standard. Autoloading is handled automatically when dependencies are managed through Composer, simply information technology is likewise possible to leverage its own autoloader in projects or scripts lacking any autoload facility:
// Prepend a base path if Predis is non available in your "include_path". require 'Predis/Autoloader.php'; Predis\Autoloader::register();
Connecting to Redis
When creating a client case without passing any connection parameter, Predis assumes 127.0.0.one
and 6379
as default host and port. The default timeout for the connect()
operation is 5 seconds:
$client = new Predis\Customer(); $client->set('foo', 'bar'); $value = $client->get('foo');
Connection parameters can be supplied either in the form of URI strings or named arrays. The latter is the preferred way to supply parameters, but URI strings tin can be useful when parameters are read from not-structured or partially-structured sources:
// Parameters passed using a named array: $client = new Predis\Client([ 'scheme' => 'tcp', 'host' => 'x.0.0.1', 'port' => 6379, ]); // Same set of parameters, passed using an URI string: $client = new Predis\Customer('tcp://10.0.0.1:6379');
Password protected servers can be accessed by calculation countersign
to the parameters set. When ACLs are enabled on Redis >= six.0, both username
and password
are required for user authentication.
Information technology is as well possible to connect to local instances of Redis using UNIX domain sockets, in this example the parameters must use the unix
scheme and specify a path for the socket file:
$client = new Predis\Client(['scheme' => 'unix', 'path' => '/path/to/redis.sock']); $customer = new Predis\Client('unix:/path/to/redis.sock');
The client tin can leverage TLS/SSL encryption to connect to secured remote Redis instances without the demand to configure an SSL proxy like stunnel. This can be useful when connecting to nodes running on various cloud hosting providers. Encryption can be enabled with using the tls
scheme and an array of suitable options passed via the ssl
parameter:
// Named array of connection parameters: $client = new Predis\Client([ 'scheme' => 'tls', 'ssl' => ['cafile' => 'private.pem', 'verify_peer' => true], ]); // Same set of parameters, but using an URI string: $client = new Predis\Customer('tls://127.0.0.1?ssl[cafile]=individual.pem&ssl[verify_peer]=1');
The connection schemes redis
(allonym of tcp
) and rediss
(allonym of tls
) are also supported, with the divergence that URI strings containing these schemes are parsed following the rules described on their respective IANA conditional registration documents.
The bodily list of supported connection parameters can vary depending on each connection backend so information technology is recommended to refer to their specific documentation or implementation for details.
Predis can aggregate multiple connections when providing an array of connectedness parameters and the appropriate option to instruct the customer near how to amass them (clustering, replication or a custom assemblage logic). Named arrays and URI strings can exist mixed when providing configurations for each node:
$client = new Predis\Client([ 'tcp://10.0.0.1?alias=first-node', ['host' => '10.0.0.2', 'allonym' => 'second-node'], ], [ 'cluster' => 'predis', ]);
See the aggregate connections section of this document for more details.
Connections to Redis are lazy significant that the client connects to a server but if and when needed. While information technology is recommended to let the client do its own stuff under the hood, there may be times when it is still desired to have control of when the connexion is opened or closed: this can hands be achieved past invoking $client->connect()
and $customer->disconnect()
. Please notation that the issue of these methods on aggregate connections may differ depending on each specific implementation.
Client configuration
Many aspects and behaviors of the client can be configured by passing specific customer options to the 2nd statement of Predis\Client::__construct()
:
$client = new Predis\Client( $parameters, ['prefix' => 'sample:']);
Options are managed using a mini DI-akin container and their values can be lazily initialized simply when needed. The customer options supported past default in Predis are:
-
prefix
: prefix string practical to every key found in commands. -
exceptions
: whether the client should throw or return responses upon Redis errors. -
connections
: list of connection backends or a connexion factory example. -
cluster
: specifies a cluster backend (predis
,redis
or callable). -
replication
: specifies a replication backend (predis
,sentinel
or callable). -
amass
: configures the client with a custom aggregate connection (callable). -
parameters
: list of default connectedness parameters for aggregate connections. -
commands
: specifies a command factory case to use through the library.
Users can also provide custom options with values or callable objects (for lazy initialization) that are stored in the options container for later use through the library.
Aggregate connections
Aggregate connections are the foundation upon which Predis implements clustering and replication and they are used to group multiple connections to unmarried Redis nodes and hibernate the specific logic needed to handle them properly depending on the context. Aggregate connections usually require an array of connexion parameters along with the appropriate client selection when creating a new customer instance.
Cluster
Predis can exist configured to work in clustering mode with a traditional client-side sharding approach to create a cluster of contained nodes and distribute the keyspace among them. This approach needs some sort of external wellness monitoring of nodes and requires the keyspace to be rebalanced manually when nodes are added or removed:
$parameters = ['tcp://10.0.0.one', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['cluster' => 'predis']; $client = new Predis\Customer( $parameters);
Along with Redis three.0, a new supervised and coordinated blazon of clustering was introduced in the grade of redis-cluster. This kind of approach uses a different algorithm to distribute the keyspaces, with Redis nodes coordinating themselves by communicating via a gossip protocol to handle health status, rebalancing, nodes discovery and request redirection. In order to connect to a cluster managed by redis-cluster, the client requires a list of its nodes (not necessarily complete since it volition automatically discover new nodes if necessary) and the cluster
customer options ready to redis
:
$parameters = ['tcp://10.0.0.one', 'tcp://10.0.0.2', 'tcp://10.0.0.3']; $options = ['cluster' => 'redis']; $client = new Predis\Customer( $parameters, $options);
Replication
The client can be configured to operate in a single main / multiple slaves setup to provide amend service availability. When using replication, Predis recognizes read-simply commands and sends them to a random slave in order to provide some sort of load-balancing and switches to the master as before long as information technology detects a control that performs whatever kind of operation that would stop upward modifying the keyspace or the value of a primal. Instead of raising a connection error when a slave fails, the client attempts to fall dorsum to a different slave amidst the ones provided in the configuration.
The basic configuration needed to utilise the customer in replication manner requires ane Redis server to be identified every bit the master (this tin exist done via connection parameters by setting the role
parameter to master
) and i or more slaves (in this case setting role
to slave
for slaves is optional):
$parameters = ['tcp://10.0.0.1?office=principal', 'tcp://10.0.0.2', 'tcp://10.0.0.iii']; $options = ['replication' => 'predis']; $client = new Predis\Client( $parameters, $options);
The above configuration has a static listing of servers and relies entirely on the customer's logic, just information technology is possible to rely on redis-sentinel
for a more robust HA environment with lookout man servers interim equally a source of authority for clients for service discovery. The minimum configuration required by the client to work with redis-lookout is a list of connection parameters pointing to a bunch of sentinel instances, the replication
option set to picket
and the service
pick set to the proper name of the service:
$sentinels = ['tcp://ten.0.0.1', 'tcp://x.0.0.ii', 'tcp://10.0.0.3']; $options = ['replication' => 'sentinel', 'service' => 'mymaster']; $client = new Predis\Client( $sentinels, $options);
If the master and slave nodes are configured to crave an authentication from clients, a password must exist provided via the global parameters
client option. This choice can also be used to specify a unlike database index. The client options array would then look like this:
$options = [ 'replication' => 'spotter', 'service' => 'mymaster', 'parameters' => [ 'password' => $secretpassword, 'database' => 10, ], ];
While Predis is able to distinguish commands performing write and read-only operations, EVAL
and EVALSHA
stand for a corner example in which the client switches to the principal node because information technology cannot tell when a Lua script is safe to be executed on slaves. While this is indeed the default behavior, when sure Lua scripts practice not perform write operations it is possible to provide an hint to tell the client to stick with slaves for their execution:
$parameters = ['tcp://ten.0.0.1?role=master', 'tcp://10.0.0.two', 'tcp://x.0.0.3']; $options = ['replication' => role () { // Set scripts that won't trigger a switch from a slave to the master node. $strategy = new Predis\Replication\ReplicationStrategy(); $strategy->setScriptReadOnly( $ LUA_SCRIPT ); return new Predis\Connectedness\Replication\MasterSlaveReplication( $strategy); }]; $client = new Predis\Customer( $parameters, $options); $client->eval( $ LUA_SCRIPT , 0); // Sticks to slave using `eval`... $customer->evalsha(sha1( $ LUA_SCRIPT ), 0); // ... and `evalsha`, too.
The examples
directory contains a few scripts that demonstrate how the client tin can be configured and used to leverage replication in both basic and complex scenarios.
Control pipelines
Pipelining tin can help with performances when many commands need to be sent to a server past reducing the latency introduced past network round-trip timings. Pipelining also works with aggregate connections. The customer tin can execute the pipeline inside a callable cake or return a pipeline instance with the power to chain commands thank you to its fluent interface:
// Executes a pipeline inside the given callable cake: $responses = $client->pipeline(office ( $pipe) { for ( $i = 0; $i < k; $i++) { $pipe->set("key:$i", str_pad( $i, 4, '0', 0)); $pipe->get("fundamental:$i"); } }); // Returns a pipeline that tin be chained thanks to its fluent interface: $responses = $client->pipeline()->ready('foo', 'bar')->get('foo')->execute();
Transactions
The client provides an brainchild for Redis transactions based on MULTI
and EXEC
with a similar interface to control pipelines:
// Executes a transaction within the given callable block: $responses = $client->transaction(function ( $tx) { $tx->gear up('foo', 'bar'); $tx->get('foo'); }); // Returns a transaction that tin can exist chained thanks to its fluent interface: $responses = $client->transaction()->set('foo', 'bar')->become('foo')->execute();
This abstraction can perform check-and-set operations cheers to Sentinel
and UNWATCH
and provides automatic retries of transactions aborted by Redis when Sentinel
ed keys are touched. For an example of a transaction using CAS you can see the following example.
Calculation new commands
While we try to update Predis to stay up to date with all the commands available in Redis, you lot might adopt to stick with an old version of the library or provide a different fashion to filter arguments or parse responses for specific commands. To accomplish that, Predis provides the ability to implement new command classes to ascertain or override commands in the default command factory used by the client:
// Define a new control by extending Predis\Control\Command: class BrandNewRedisCommand extends Predis\Control\Control { public function getId() { return 'NEWCMD'; } } // Inject your command in the electric current command factory: $customer = new Predis\Client( $parameters, [ 'commands' => [ 'newcmd' => 'BrandNewRedisCommand', ], ]); $response = $customer->newcmd();
At that place is also a method to transport raw commands without filtering their arguments or parsing responses. Users must provide the listing of arguments for the control as an array, post-obit the signatures equally defined past the Redis documentation for commands:
$response = $customer->executeRaw(['SET', 'foo', 'bar']);
Script commands
While it is possible to leverage Lua scripting on Redis 2.6+ using directly EVAL
and EVALSHA
, Predis offers script commands every bit an higher level abstraction built upon them to make things simple. Script commands tin be registered in the command manufactory used by the client and are attainable as if they were apparently Redis commands, but they define Lua scripts that become transmitted to the server for remote execution. Internally they employ EVALSHA
past default and place a script by its SHA1 hash to salve bandwidth, but EVAL
is used as a fall back when needed:
// Define a new script control by extending Predis\Command\ScriptCommand: class ListPushRandomValue extends Predis\Control\ScriptCommand { public role getKeysCount() { return 1; } public function getScript() { return <<<LUA math.randomseed(ARGV[one]) local rnd = tostring(math.random()) redis.call('lpush', KEYS[ane], rnd) return rnd LUA; } } // Inject the script control in the current control manufactory: $customer = new Predis\Client( $parameters, [ 'commands' => [ 'lpushrand' => 'ListPushRandomValue', ], ]); $response = $customer->lpushrand('random_values', $seed = mt_rand());
Customizable connection backends
Predis can use different connectedness backends to connect to Redis. Two of them leverage a 3rd party extension such as phpiredis resulting in major performance gains particularly when dealing with big multibulk responses. While one is based on PHP streams, the other is based on socket resources provided by ext-socket
. Both support TCP/IP and UNIX domain sockets:
$client = new Predis\Client('tcp://127.0.0.1', [ 'connections' => [ 'tcp' => 'Predis\Connection\PhpiredisStreamConnection', // PHP stream resource 'unix' => 'Predis\Connectedness\PhpiredisSocketConnection', // ext-socket resources ], ]);
The client can also be configured to rely on a phpiredis-backend by specifying a descriptive string for the connections
customer option. Supported string values are:
-
phpiredis-stream
mapstcp
,redis
andunix
toPredis\Connection\PhpiredisStreamConnection
-
phpiredis-socket
mapstcp
,redis
andunix
toPredis\Connection\PhpiredisSocketConnection
-
phpiredis
is but an alias ofphpiredis-stream
$client = new Predis\Customer('tcp://127.0.0.1', ['connections' => 'phpiredis']);
Developers can create their own connectedness classes to support whole new network backends, extend existing classes or provide completely different implementations. Connection classes must implement Predis\Connexion\NodeConnectionInterface
or extend Predis\Connection\AbstractConnection
:
grade MyConnectionClass implements Predis\Connection\NodeConnectionInterface { // Implementation goes here... } // Use MyConnectionClass to handle connections for the `tcp` scheme: $client = new Predis\Client('tcp://127.0.0.1', [ 'connections' => ['tcp' => 'MyConnectionClass'], ]);
For a more in-depth insight on how to create new connection backends you can refer to the actual implementation of the standard connexion classes available in the Predis\Connectedness
namespace.
Evolution
Reporting bugs and contributing code
Contributions to Predis are highly appreciated either in the form of pull requests for new features, problems fixes, or just bug reports. We simply ask you to adhere to a bones set of rules before submitting your changes or filing bugs on the effect tracker to make it easier for everyone to stay consistent while working on the projection.
Test suite
ATTENTION: Practice not ever run the test suite shipped with Predis against instances of Redis running in production environments or containing data you lot are interested in!
Predis has a comprehensive test suite covering every aspect of the library and that tin can optionally perform integration tests confronting a running case of Redis (required >= two.4.0 in order to verify the correct beliefs of the implementation of each command. Integration tests for unsupported Redis commands are automatically skipped. If you do not have Redis up and running, integration tests can exist disabled. Meet the tests README for more details nigh testing this library.
Predis uses GitHub Actions for continuous integration and the history for by and current builds can be found on its deportment page.
Other
Projection related links
- Source lawmaking
- Wiki
- Result tracker
Author
- Daniele Alessandri (twitter)
- Till Krüss (Twitter)
License
The code for Predis is distributed under the terms of the MIT license (see LICENSE).
GitHub
https://github.com/predis/predisSource: https://bestofphp.com/repo/predis-predis-php-nosql
0 Response to "Laravel Aws Redis Error While Reading Line From the Server."
Post a Comment