php使用redis

Posted 水杉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php使用redis相关的知识,希望对你有一定的参考价值。

  在 http://www.redis.net.cn/ 能找到所有关于redis的信息,包括安装、命令、在编程语言中的使用等等。这里就不讲如何安装redis了,因为在上面的网站中都能找到。下面直接讲redis是如何在php中使用的,这里我选择的是phpredis扩展。

1. 下载phpredis扩展  

  执行phpinfo()函数,根据下面截图中的“NTS”和“VCn”选择对应的压缩包,https://github.com/phpredis/phpredis/downloads。另外注意,PHP版本也要对应好。

 

2. PHP配置安装扩展

  首先把压缩包中的 php_igbinary.dll和php_redis.dll 文件放到PHP安装目录的 ext 目录中

  然后在 php.ini 添加如下配置

extension=php_igbinary.dll
extension=php_redis.dll

 

3. 重启apache,执行phpinfo()函数,会发现多了redis的扩展。

 

 4. 开启Redis服务,测试

    $redis = new Redis();
    //连接redis服务器
    $redis->connect(\'127.0.0.1\', \'6379\');
    echo "Connection to server sucessfully <br/>";

    //查看服务是否运行
    echo "Server is running: " . $redis->ping();

结果如下,连接redis服务器成功

Connection to server sucessfully 
Server is running: +PONG

 

至此,我们可以在php中痛痛快快的使用redis了。

 1     $redis = new Redis();
 2     //连接redis服务器
 3     $redis->connect(\'127.0.0.1\', \'6379\');
 4 
 5 
 6     $key = "key";
 7     $val = "val";
 8 
 9     //redis key操作
10     $redis->exists($key);           //判断key值是否存在
11     $redis->expire($key, 10);       //设置key在10秒后过期
12 
13     //redis string 字符串
14     $redis->set($key, $val);
15     $redis->incr($key);         //key值+1,除非val是整数,否则函数执行失败
16     $redis->decr($key);         //key值-1,同上
17     $redis->append($key, "ue"); //追加key值内容
18     $redis->strlen($key);       //返回key值的长度
19 
20     //当第一次设置key值后,key值的数据类型就不能改变了。
21     $redis->del($key);  //删除key值
22 
23     //redis hash 哈希
24     $redis->hset($key, \'field1\', \'val1\');   //设置一个key-value键值对
25     $redis->hmset($key, array(\'field2\'=>\'val2\', \'field3\'=>\'val3\'));    //设置多个k-v键值对
26     $redis->hget($key, \'field2\');           //获取hash其中的一个键值
27     $redis->hmget($key, array(\'field2\', \'field1\'));    //获取hash的多个键值
28     $redis->hgetall($key);  //获取hash中所有的键值对
29     $redis->hlen($key);     //获取hash中键值对的个数
30     $redis->hkeys($key);   //获取hash中所有的键
31     $redis->hvals($key);    //获取hash中所有的值
32     $redis->del($key);  //删除key值
33 
34     //redis list 列表
35     $index = $start = 0;
36     $redis->lpush($key, \'val1\', \'val2\');    //在list的开头添加多个值
37     $redis->lpop($key); //移除并获取list的第一个元素
38     $redis->rpop($key); //移除并获取list的最后一个元素
39     $stop = $redis->llen($key) - 1; //获取list的长度
40     $redis->lindex($key, $index);   //通过索引获取list元素
41     $redis->lrange($key, $start, $stop);    //获取指定范围内的元素
42 
43     $redis->del($key);
44 
45     //redis set 无序集合
46     $redis->sadd($key, \'val1\', \'val2\'); //向集合中添加多个元素
47     $redis->scard($key);    //获取集合元素个数
48     $redis->spop($key); //移除并获取集合内随机一个元素
49     $redis->srem($key, \'val1\', \'val2\'); //移除集合的多个元素
50     $redis->sismember($key, \'val1\');    //判断元素是否存在于集合内
51 
52     $redis->del($key);
53     //redis sorted set 有序集合
54     //有序集合里的元素都和一个分数score关联,就靠这个分数score对元素进行排序
55     $redis->zadd($key, $score1, $val1, $score2, $val2); //向集合内添加多个元素
56     $redis->zcard($key);    //获取集合内元素总数
57     $redis->zcount($key, $minScore, $maxScore); //获取集合内分类范围内的元素
58     $redis->zrem($key, $member1, $member2); //移除集合内多个元素

 

附:Redis类的源码

   1 <?php
   2 /**
   3  * Helper autocomplete for php redis extension
   4  * @author Max Kamashev <max.kamashev@gmail.com>
   5  * @link https://github.com/ukko/phpredis-phpdoc
   6  *
   7  * @method echo string $string Sends a string to Redis, which replies with the same string
   8  *
   9  * @method  eval( $script, $args = array(), $numKeys = 0 )
  10  *  Evaluate a LUA script serverside
  11  *  @param  string  $script
  12  *  @param  array   $args
  13  *  @param  int     $numKeys
  14  *  @return Mixed.  What is returned depends on what the LUA script itself returns, which could be a scalar value
  15  *  (int/string), or an array. Arrays that are returned can also contain other arrays, if that\'s how it was set up in
  16  *  your LUA script.  If there is an error executing the LUA script, the getLastError() function can tell you the
  17  *  message that came back from Redis (e.g. compile error).
  18  *  @link   http://redis.io/commands/eval
  19  *  @example
  20  *  <pre>
  21  *  $redis->eval("return 1"); // Returns an integer: 1
  22  *  $redis->eval("return {1,2,3}"); // Returns Array(1,2,3)
  23  *  $redis->del(\'mylist\');
  24  *  $redis->rpush(\'mylist\',\'a\');
  25  *  $redis->rpush(\'mylist\',\'b\');
  26  *  $redis->rpush(\'mylist\',\'c\');
  27  *  // Nested response:  Array(1,2,3,Array(\'a\',\'b\',\'c\'));
  28  *  $redis->eval("return {1,2,3,redis.call(\'lrange\',\'mylist\',0,-1)}}");
  29  * </pre>
  30  *
  31  */
  32 class Redis
  33 {
  34     const AFTER                 = \'after\';
  35     const BEFORE                = \'before\';
  36 
  37     /**
  38      * Options
  39      */
  40     const OPT_SERIALIZER        = 1;
  41     const OPT_PREFIX            = 2;
  42     const OPT_READ_TIMEOUT = 3;
  43     const OPT_SCAN = 4;
  44 
  45     /**
  46      * Serializers
  47      */
  48     const SERIALIZER_NONE       = 0;
  49     const SERIALIZER_PHP        = 1;
  50     const SERIALIZER_IGBINARY   = 2;
  51 
  52     /**
  53      * Multi
  54      */
  55     const ATOMIC = 0;
  56     const MULTI = 1;
  57     const PIPELINE = 2;
  58 
  59     /**
  60      * Type
  61      */
  62     const REDIS_NOT_FOUND       = 0;
  63     const REDIS_STRING          = 1;
  64     const REDIS_SET             = 2;
  65     const REDIS_LIST            = 3;
  66     const REDIS_ZSET            = 4;
  67     const REDIS_HASH            = 5;
  68 
  69 
  70     /**
  71      * Scan
  72      */
  73      const SCAN_NORETRY = 0;
  74      const SCAN_RETRY = 1;
  75 
  76      /**
  77      * Creates a Redis client
  78      *
  79      * @example $redis = new Redis();
  80      */
  81     public function __construct( ) {}
  82 
  83     /**
  84      * Connects to a Redis instance.
  85      *
  86      * @param string    $host       can be a host, or the path to a unix domain socket
  87      * @param int       $port       optional
  88      * @param float     $timeout    value in seconds (optional, default is 0.0 meaning unlimited)
  89      * @return bool                 TRUE on success, FALSE on error.
  90      * <pre>
  91      * $redis->connect(\'127.0.0.1\', 6379);
  92      * $redis->connect(\'127.0.0.1\');            // port 6379 by default
  93      * $redis->connect(\'127.0.0.1\', 6379, 2.5); // 2.5 sec timeout.
  94      * $redis->connect(\'/tmp/redis.sock\');      // unix domain socket.
  95      * </pre>
  96      */
  97     public function connect( $host, $port = 6379, $timeout = 0.0 ) {}
  98 
  99     /**
 100      * Set the string value in argument as value of the key, with a time to live.
 101      *
 102      * @param   string $key
 103      * @param   int $ttl in milliseconds
 104      * @param   string $value
 105      * @return  bool:   TRUE if the command is successful.
 106      * @link    http://redis.io/commands/setex
 107      * $redis->psetex(\'key\', 100, \'value\'); // sets key → value, with 0.1 sec TTL.
 108      */
 109     public function psetex($key, $ttl, $value) {}
 110 
 111     /**
 112      * Scan a set for members.
 113      *
 114      * @see scan()
 115      * @param   string $key
 116      * @param   int $iterator
 117      * @param   string $pattern
 118      * @param   int $count
 119      * @return  array|bool
 120      */
 121     public function sScan($key, $iterator, $pattern = \'\', $count = 0) {}
 122 
 123     /**
 124      * Scan the keyspace for keys.
 125      *
 126      * @param   int $iterator
 127      * @param   string $pattern
 128      * @param   int $count How many keys to return in a go (only a sugestion to Redis)
 129      * @return  array|bool   an array of keys or FALSE if there are no more keys
 130      * @link    http://redis.io/commands/scan
 131      * <pre>
 132      * $it = NULL; // Initialize our iterator to NULL
 133      * $redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); // retry when we get no keys back
 134      * while($arr_keys = $redis->scan($it)) {
 135      *   foreach($arr_keys as $str_key) {
 136      *     echo "Here is a key: $str_key\\n";
 137      *   }
 138      *   echo "No more keys to scan!\\n";
 139      * }
 140      * </pre>
 141      */
 142     public function scan($iterator, $pattern = \'\', $count = 0) {}
 143 
 144     /**
 145      * Scan a sorted set for members, with optional pattern and count.
 146      *
 147      * @see scan()
 148      * @param   string  $key
 149      * @param   int $iterator
 150      * @param   string  $pattern
 151      * @param   int $count
 152      * @return  array|bool
 153      */
 154     public function zScan($key, $iterator, $pattern = \'\', $count = 0) {}
 155 
 156     /**
 157      * Scan a HASH value for members, with an optional pattern and count.
 158      *
 159      * @see scan()
 160      * @param   string $key
 161      * @param   int $iterator
 162      * @param   string $pattern
 163      * @param   int $count
 164      * @return  array
 165      */
 166     public function hScan($key, $iterator, $pattern = \'\', $count = 0) {}
 167 
 168 
 169 
 170     /**
 171      * Issue the CLIENT command with various arguments.
 172      * @param   string $command list | getname | setname | kill
 173      * @param   string $arg
 174      * @return  mixed
 175      * @link    http://redis.io/commands/client-list
 176      * @link    http://redis.io/commands/client-getname
 177      * @link    http://redis.io/commands/client-setname
 178      * @link    http://redis.io/commands/client-kill
 179      * <pre>
 180      * $redis->client(\'list\');
 181      * $redis->client(\'getname\');
 182      * $redis->client(\'setname\', \'somename\');
 183      * $redis->client(\'kill\', <ip:port>);
 184      * </pre>
 185      *
 186      *
 187      * CLIENT LIST will return an array of arrays with client information.
 188      * CLIENT GETNAME will return the client name or false if none has been set
 189      * CLIENT SETNAME will return true if it can be set and false if not
 190      * CLIENT KILL will return true if the client can be killed, and false if not
 191      */
 192     public function client($command, $arg = \'\') {}
 193 
 194     /**
 195      * Access the Redis slow log.
 196      *
 197      * @param   string $command get | len | reset
 198      * @return  mixed
 199      * @link    http://redis.io/commands/slowlog
 200      * <pre>
 201      * // Get ten slowlog entries
 202      * $redis->slowlog(\'get\', 10);
 203      *
 204      * // Get the default number of slowlog entries
 205      * $redis->slowlog(\'get\');
 206      *
 207      * // Reset our slowlog
 208      * $redis->slowlog(\'reset\');
 209      *
 210      * // Retrieve slowlog length
 211      * $redis->slowlog(\'len\');
 212      * </pre>
 213      */
 214     public function slowlog($command) {}
 215 
 216     /**
 217      * @see connect()
 218      * @param string    $host
 219      * @param int       $port
 220      * @param float     $timeout
 221      */
 222     public function open( $host, $port = 6379, $timeout = 0.0 ) {}
 223 
 224     /**
 225      * Connects to a Redis instance or reuse a connection already established with pconnect/popen.
 226      *
 227      * The connection will not be closed on close or end of request until the php process ends.
 228      * So be patient on to many open FD\'s (specially on redis server side) when using persistent connections on
 229      * many servers connecting to one redis server.
 230      *
 231      * Also more than one persistent connection can be made identified by either host + port + timeout
 232      * or unix socket + timeout.
 233      *
 234      * This feature is not available in threaded versions. pconnect and popen then working like their non persistent
 235      * equivalents.
 236      *
 237      * @param string    $host       can be a host, or the path to a unix domain socket
 238      * @param int       $port       optional
 239      * @param float     $timeout    value in seconds (optional, default is 0 meaning unlimited)
 240      * @return bool                 TRUE on success, FALSE on ertcnror.
 241      * <pre>
 242      * $redis->connect(\'127.0.0.1\', 6379);
 243      * $redis->connect(\'127.0.0.1\');            // port 6379 by default
 244      * $redis->connect(\'127.0.0.1\', 6379, 2.5); // 2.5 sec timeout.
 245      * $redis->connect(\'/tmp/redis.sock\');      // unix domain socket.
 246      * </pre>
 247      */
 248     public function pconnect( $host, $port = 6379, $timeout = 0.0 ) {}
 249 
 250     /**
 251      * @see pconnect()
 252      * @param string    $host
 253      * @param int       $port
 254      * @param float     $timeout
 255      */
 256     public function popen( $host, $port = 6379, $timeout = 0.0 ) {}
 257 
 258     /**
 259      * Disconnects from the Redis instance, except when pconnect is used.
 260      */
 261     public function close( ) {}
 262 
 263     /**
 264      * Set client option.
 265      *
 266      * @param   string  $name    parameter name
 267      * @param   string  $value   parameter value
 268      * @return  bool:   TRUE on success, FALSE on error.
 269      * @example
 270      * <pre>
 271      * $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE);        // don\'t serialize data
 272      * $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_PHP);         // use built-in serialize/unserialize
 273      * $redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);    // use igBinary serialize/unserialize
 274      * $redis->setOption(Redis::OPT_PREFIX, \'myAppName:\');                      // use custom prefix on all keys
 275      * </pre>
 276      */
 277     public function setOption( $name, $value ) {}
 278 
 279     /**
 280      * Get client option
 281      *
 282      * @param   string  $name parameter name
 283      * @return  int     Parameter value.
 284      * @example
 285      * // return Redis::SERIALIZER_NONE, Redis::SERIALIZER_PHP, or Redis::SERIALIZER_IGBINARY.
 286      * $redis->getOption(Redis::OPT_SERIALIZER);
 287      */
 288     public function getOption( $name ) {}
 289 
 290     /**
 291      * Check the current connection status
 292      *
 293      * @return  string STRING: +PONG on success. Throws a RedisException object on connectivity error, as described above.
 294      * @link    http://redis.io/commands/ping
 295      */
 296     public function ping( ) {}
 297 
 298     /**
 299      * Get the value related to the specified key
 300      *
 301      * @param   string  $key
 302      * @return  string|bool: If key didn\'t exist, FALSE is returned. Otherwise, the value related to this key is returned.
 303      * @link    http://redis.io/commands/get
 304      * @example $redis->get(\'key\');
 305      */
 306     public function get( $key ) {}
 307 
 308 
 309     /**
 310      * Set the string value in argument as value of the key.
 311      *
 312      * @param   string  $key
 313      * @param   string  $value
 314      * @param   int   $timeout [optional] Calling setex() is preferred if you want a timeout.
 315      * @return  bool:   TRUE if the command is successful.
 316      * @link    http://redis.io/commands/set
 317      * @example $redis->set(\'key\', \'value\');
 318      */
 319     public function set( $key, $value, $timeout = 0 ) {}
 320 
 321     /**
 322      * Set the string value in argument as value of the key, with a time to live.
 323      *
 324     

以上是关于php使用redis的主要内容,如果未能解决你的问题,请参考以下文章

html PHP代码片段: - AJAX基本示例:此代码演示了使用PHP和JavaScript实现的基本AJAX功能。

如何使用sublime代码片段快速输入PHP头部版本声明

超级有用的9个PHP代码片段

PHP必用代码片段

超实用的php代码片段

比较有用的php代码片段