Redis是一种常用的非关系型数据库,主要用作数据缓存,数据保存形式为key-value,键值相互映射.它的数据存储跟MySQL不同,它数据存储在内存之中,所以数据读取相对而言很快,用来做高并发非常不错.
ThinkPhP5.0自带了Redis扩展,在使用之前先下载php_redis.dll 网址 http://windows.php.net/downloads/pecl/releases/redis/2.2.7/ ;根据自己windows操作系统选择相应的版本,我自己是系统64位,安装的是VC2012 所以下载的是php_redis-2.2.7-5.6-ts-vc11-x64.zip
下载好压缩包之后,把里面的php_redis.dll 解压到D:\wamp\bin\php\php5.6.25\ext (根据自己wamp所在的盘自己选择),然后在php.ini里面添加extension=php_redis.dll,重新启动apache就可以了;
下面是我自己测试的代码,可以使用,封装的不多,可以根据自己的需求去动手封装
extend 是thinkPHP5.0的扩展类库目录,可以自己去定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | namespaceMy; //目录我放在thinkphp5.0/extend/MyclassRedisPackage{protectedstatic$handler= null;protected$options= [‘host‘=>‘127.0.0.1‘,‘port‘=> 6379,‘password‘=>‘‘,‘select‘=> 0,‘timeout‘=> 0, //关闭时间 0:代表不关闭‘expire‘=> 0,‘persistent‘=> false,‘prefix‘=>‘‘,];publicfunction__construct($options= []){if(!extension_loaded(‘redis‘)) {//判断是否有扩展(如果你的apache没reids扩展就会抛出这个异常)thrownew\BadFunctionCallException(‘not support: redis‘);}if(!empty($options)) {$this->options =array_merge($this->options,$options);}$func=$this->options[‘persistent‘] ?‘pconnect‘:‘connect‘;//判断是否长连接self::$handler=new\Redis;self::$handler->$func($this->options[‘host‘],$this->options[‘port‘],$this->options[‘timeout‘]);if(‘‘!=$this->options[‘password‘]) {self::$handler->auth($this->options[‘password‘]);}if(0 !=$this->options[‘select‘]) {self::$handler->select($this->options[‘select‘]);}}/*** 写入缓存* @param string $key 键名* @param string $value 键值* @param int $exprie 过期时间 0:永不过期* @return bool*/publicstaticfunctionset($key,$value,$exprie= 0){if($exprie== 0) {$set= self::$handler->set($key,$value);}else{$set= self::$handler->setex($key,$exprie,$value);}return$set;}/*** 读取缓存* @param string $key 键值* @return mixed*/publicstaticfunctionget($key){$fun=is_array($key) ?‘Mget‘:‘get‘;returnself::$handler->{$fun}($key);}/*** 获取值长度* @param string $key* @return int*/publicstaticfunctionlLen($key){returnself::$handler->lLen($key);}/*** 将一个或多个值插入到列表头部* @param $key* @param $value* @return int*/publicstaticfunctionLPush($key,$value,$value2= null,$valueN= null){returnself::$handler->lPush($key,$value,$value2,$valueN);}/*** 移出并获取列表的第一个元素* @param string $key* @return string*/publicstaticfunctionlPop($key){returnself::$handler->lPop($key);}} |
ThinkPHP5.0中Redis的使用和封装
原文地址:http://www.cnblogs.com/wmm123/p/7832689.html