To better understand the Redis protocol, we use PHP to implement a client class that supports most of the commands.
Redis's agreement can refer to this article http://redis.cn/topics/protocol.html
The code is as follows:
<?php
namespace Xtgxiso;
Class Redis {
Private $redis _socket = false;
Private $cmd = ';
Public function __construct ($host = ' 127.0.0.1 ', $port =6379, $timeout = 3) {
$this->redis_socket = stream_socket_client ("tcp://". $host ":". $port, $errno, $errstr, $timeout);
if (! $this->redis_socket) {
throw new Exception ("{$errno}-{$errstr}");
}
}
Public Function __destruct () {
Fclose ($this->redis_socket);
}
Public Function __call ($name, $args) {
$crlf = "\ r \ n";
Array_unshift ($args, $name);
$command = ' * '. Count ($args). $crlf;
foreach ($args as $arg) {
$command. = ' $ '. Strlen ($arg). $crlf. $arg. $crlf;
}
$fwrite = fwrite ($this->redis_socket, $command);
if ($fwrite = = FALSE | | $fwrite <= 0) {
throw new Exception (' Failed to write entire command to stream ');
}
return $this->readresponse ();
}
Private Function Readresponse () {
$reply = Trim (fgets ($this->redis_socket, 1024));
Switch (substr ($reply, 0, 1)) {
Case '-':
throw new Exception (Trim (substr ($reply, 4));
Break
Case ' + ':
$response = substr (Trim ($reply), 1);
if ($response = = = ' OK ') {
$response = TRUE;
}
Break
Case ' $ ':
$response = NULL;
if ($reply = = ' $-1 ') {
Break
}
$read = 0;
$size = Intval (substr ($reply, 1));
if ($size > 0) {
do {
$block _size = ($size-$read) > 1024? 1024: ($size-$read);
$r = Fread ($this->redis_socket, $block _size);
if ($r = = FALSE) {
throw new Exception (' Failed to read response from Stream ');
} else {
$read + + strlen ($r);
$response. = $r;
}
while ($read < $size);
}
Fread ($this->redis_socket, 2); /* Discard CRLF * *
Break
/* Multi-bulk Reply * *
Case ' * ':
$count = Intval (substr ($reply, 1));
if ($count = = '-1 ') {
return NULL;
}
$response = Array ();
for ($i = 0; $i < $count; $i + +) {
$response [] = $this->readresponse ();
}
Break
/* Integer Reply * *
Case ': ':
$response = Intval (substr (Trim ($reply), 1));
Break
Default
throw new Redisexception ("Unknown response: {$reply}");
Break
}
return $response;
}
}
/*
$redis = new Client_test ();
Var_dump ($redis->auth ("123456"));
Var_dump ($redis->set ("Xtgxiso", ' abc '));
Var_dump ($redis->get ("Xtgxiso"));
*/
By implementing, we have a basic understanding of the Redis protocol.