Redis-predis extension

Source: Internet
Author: User
Tags autoloader cas eval lua redis redis cluster redis server

Predis

The Predis is intended for use in Redis for more than PHP 5.3, including the use of clusters. Key Features support various versions of Redis (from 2.0 to 3.0 and unstable) using hashing or user-defined methods for client shard support for nodes in a cluster Redis-cluster (Cluster) (redis>= 3.0). Support for master/slave fabric read-write separation supports all known Redis client command usage

Predis download addresses are: Pear Channel and github mode. Load Dependent Packages

Predis relies on PHP's automatic loading function, loading its files when needed and complying with the PSR-4 standard.
Use the following:

Load from the Predis root directory. Unless the file is in include_path
require ' predis/autoloader.php ';

Predis\autoloader::register ();
Connect to Redis

If you do not add any parameters to the connection, 127.0.0.1 and 6379 will be the default host and port by default and the connection time-out is 5 seconds. Such as:

$client = new Predis\client ();
$client->set (' foo ', ' Bar ');
$value = $client->get (' foo ');

If you need to add a connection parameter, either in the URI or in the form of an array. Such as:

Array form
$client = new Predis\client ([
    ' scheme ' = ' tcp ',
    ' host ' = '   10.0.0.1 ',
    ' port '   = > 6379,
]);

URI form:
$client = new Predis\client (' tcp://10.0.0.1:6379 ');

When using an array form. The Predis is automatically converted to cluster mode and uses the client's Shard logic.
In addition, parameters can also be mixed with URIs and arrays, such as:

$client = new Predis\client ([
    ' Tcp://10.0.0.1?alias=first-node ',
    [' host ' = ' 10.0.0.2 ', ' Alias ' = ') ' Second-node '],
]);
Client Configuration

More configuration parameters for the Client can be passed in by the second parameter:

$client = new \predis\client (
    $connection _parameters,
    [' profile ' = ' 2.8 ', ' prefix ' = ' sample: ']
);

Redis gives the required parameter defaults, which are mainly: profile: For a specific version of the configuration, because different versions may differ in the same operation. Prefix: automatically adds a prefix to the key to be processed. Exceptions:redis whether the result is returned when an error occurs. Connections: The connection factory to be used by the client. cluster: Which background (Predis, Redis, or client configuration) is used in the cluster. Replication: Which background (Predis or client configuration) is used in the master/from. Aggregate: Merge connection mode (overwrite cluster and replication). Merge Connections

The Predis supports cluster and master/slave fabric connections.
By default, using the client's Shard logic, you can also use the way that the Redis server provides: Redis cluster.
In the master/slave structure, the Predis supports a master multi-slave form and connects to the host during a read operation when the slave is connected to a write operation. master/slave structure

A master/slave configuration can be made when the client connects. When configured, the slave is connected when the read operation is performed, and the host is connected when the write operation is performed. Implement read-write separation.
The following are the main/slave configurations for the comparison base:

$parameters = [' Tcp://10.0.0.1?alias=master ', ' tcp://10.0.0.2?alias=slave-01 '];
$options    = [' Replication ' = true];

$client = new Predis\client ($parameters, $options);

Although Predis can recognize read/write operations, EVAL, Evalsha is a two special case. Because the client does not know if there is a write operation in the Lua script, the two operations are usually performed on Master.
Although this is a default behavior, some Lua scripts do not include write operations, and the client may still execute on slaves. Can be specified by configuration.

$LUA _script = ".... Some LUA code ...";
$parameters = [' Tcp://10.0.0.1?alias=master ', ' tcp://10.0.0.2?alias=slave-01 '];
$options    = [' replication ' = = function () {
    //force specified as slave on execution, not switch to master
    $strategy = new Predis\replicatio N\replicationstrategy ();
    $strategy-Setscriptreadonly ($LUA _script);

    return new Predis\connection\aggregate\masterslavereplication ($strategy);
}];

$client = new Predis\client ($parameters, $options);
$client, eval ($LUA _script, 0);             Sticks to slave using ' eval '
... $client-Evalsha (SHA1 ($LUA _script), 0);    ... and ' Evalsha ', too.
Cluster

Cluster functionality can be achieved by passing simple and configuration, and is a shard on the client. However, if you want to use the Redis-cluster feature (available in the version after Redis 3.0). Can be configured as follows:

$parameters = [' tcp://10.0.0.1 ', ' tcp://10.0.0.2 '];
$options    = [' cluster ' = ' redis '];

$client = new Predis\client ($parameters, $options);

When using Redis-cluster, it is not necessary to pass all the nodes in the cluster into the parameters, only a few can be passed. Predis will automatically get all the hash slot mappings from a single server.

Note : Currently Predis does not support the master/slave structure command pipeline in Redis-cluster

Pipelines are useful for improving performance issues when a large number of commands are sent. It can reduce the latency of network round trips. For example, there are two commands, and the data requires:
-Send command to server
-Server Execution commands
-Return structure to client

Each action is performed by the pipeline, which means that multiple commands can be packaged and sent together to the server, and all the commands are executed before the final result is returned.
There are two ways to use a pipeline, one through a callback function, and one through an interface:

The callback method executes the command channel:
$responses = $client->pipeline (function ($pipe) {for
    ($i = 0; $i <; $i + +) {
        $pipe- >set ("Key: $i", Str_pad ($i, 4, ' 0 ', 0));
        $pipe->get ("Key: $i");
    }
);

The interface form uses the command channel:
$responses = $client->pipeline ()->set (' foo ', ' Bar ')->get (' foo ')->execute ();
Transactions

Redis can implement transactional functionality using the MULTI and EXEC commands. Here you can use the command channel directly:

Callback method:
$responses = $client->transaction (function ($tx) {
    $tx->set (' foo ', ' Bar ');
    $tx->get (' foo ');
});

Interface mode:
$responses = $client->transaction ()->set (' foo ', ' Bar ')->get (' foo ')->execute ();

We can use WATCH and unwatch to implement CAS (check and set). Such as:

function Zpop ($client, $key)
{
    $element = null;
    $options = Array (
        ' cas ' = =   true,    //Use the CAS-way
        ' watch ' and $key,    //Key
        ' retry ' to monitor) ' = 3,< c9/>//Number of Retries when error occurs
    );

    $client->transaction ($options, function ($TX) use ($key, & $element) {
        @list ($element) = $tx->zrange ($ Key, 0, 0);

        if (Isset ($element)) {
            $tx->multi ();   Open transaction
            $tx->zrem ($key, $element);
        }
    );

    return $element;
}

$client = new Predis\client ($single _server);
$zpopped = Zpop ($client, ' zset ');
Custom Commands

If we upgrade Redis to a new version, and some of the commands are handled differently, but we want to use the previous logic, we can customize the command:

Customizing a class, inheriting Predis\command\command:
class Brandnewrediscommand extends Predis\command\command
{public
    function GetId ()
    {
        return ' newcmd ';
    }
}

Register the new custom command:
$client = new Predis\client ();
$client->getprofile ()->definecommand (' Newcmd ', ' Brandnewrediscommand ');

$response = $client->newcmd ();
LUA Command

The version after Redis 2.6 can be used
EVAL and Evalsha to execute LUA scripts.
Predis supports this feature with a simple interface.
LUA scripts can be either on the server or through parameters.
By default, Evalsha can also be used to alternate EVAL:

Defines a script execution command that inherits Predis\command\scriptcommand:
class Listpushrandomvalue extends Predis\command\scriptcommand
{public
    function Getkeyscount ()
    {
        return 1;
    }

    Public Function GetScript ()
    {
        return <<
    }
}

//Register a new command:
$client = new Predis\client () ;
$client->getprofile ()->definecommand (' Lpushrand ', ' listpushrandomvalue ');

$response = $client->lpushrand (' random_values ', $seed = Mt_rand ());
Performance Native Test

Predis is an extension of pure PHP, so its performance may be somewhat inadequate. But it should be enough in practice. Here are some test data, using Php5.5.6,redis 2.8:

21000 set/seconds key and value both use the size
21000 get/seconds
use _keys *_ command can query to 30,000 keys in 0.130 seconds

Similar extensions to Predis are: Phpredis, an extension written in C. The test performance results are as follows:

30100 set/seconds key and value both use the size
29400 get/seconds
use _keys *_ command can query to 30,000 keys in 0.035 seconds

Phpredis looks a lot faster. But actually the difference is not too much, and one is written in C, one is the extension of pure PHP. And the above test is simple enough to be conclusive. Here's a look at tests similar to the actual production environment. External network environment test

Here are some tests that connect to the local computer, try the following connection to the remote server:

Predis:
3200 set/seconds key and value both use the size of the type
3200 get/seconds
using _keys *_ command can query to 30,000 keys in 0.132 seconds

Phpredis :
3500 set/sec key and value both use the size
3500 get/seconds
use _keys *_ command can query to 30,000 keys in 0.045 seconds

You can see that the two are similar in efficiency, because the latency of the site can be a very important performance issue. Predis can use the command channel, saving a lot of time. Last Selection

The Predis can be compatible with each version of Redis (currently 1.2 to 2.8), and can be customized with custom commands to accommodate different versions of the differences.
The advantages of Phpredis in this machine are some.
Or, you can use both.

Source: http://blog.sina.com.cn/s/blog_5f54f0be0102vygj.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.