Redis是一款开源的可基于内存亦可持久化的日志型、Key-Value数据库,是目前最快的NOSQL数据库之一,单从做缓存应用来讲比Memcache更加优秀。要操作Redis缓存,我们必须选择一种客户端。Redis官方已经列出了很多的PHP的客户端,这里推荐另外一个非常受欢迎的php客户端–phpredis。
下文中我们将使用phpredis来于redis进行交互,主要包含以下几点;
(一)配置phpredis
(二)使用phpredis
(三)phpredis中常用的方法
(四)php程序中使用redis的完整实例
(一)配置phpredis
首先从github上将phpredis下载下来,https://github.com/nicolasff/phpredis
下载之后解压,Ubuntu上可以使用如下命令安装:
cd phpredis
sudo phpize
sudo ./configure
sudo make
sudo make install
现在phpredis扩展已经打进来了,复制模块到php扩展目录
sudo cp modules/redis.so {php-config–extension-dir}
现在,修改php.ini,增加如下
extension = redis.so
或者如下操作:
sudo echo “extension=redis.so” > /etc/php5/conf.d/redis.ini
(二)使用phpredis
phpredis扩展引入了Redis类,基于这个类我们可以进行各种操作了。
1.Redis类
通常用于连接redis,我们可以使用如下代码创建实例
$redisClient = new Redis();
2.RedisException类
这个类是用来进行异常捕获的,代码样例如下:
try{
if( $socket = fsockopen( $host, $port, $errorNo, $errorStr )){
if( $errorNo ){
throw new RedisException(“Socket cannot be opened”);
}
}
}catch( Exception $e ){
echo $e -> getMessage( );
}
(三)常用的phpredis方法
1.Connect
用来连接redis实例
$redisClient -> connect(“hostOrUnixPath”, “port”, “timeOut”, “reservedInterval” );
例如:
$objRedis = new Redis(); $objRedis->connect( ‘localhost’, 6379 ); $objRedis->connect( ’127.0.0.1′ ); // By default it will take port 6379 $objRedis->connect( ’127.0.0.1′, 6379, 3.5 ); // Giving timeOut of 3.5 sec $objRedis->connect( ‘/var/temp/redis/redis.sock’ ); // Unix domain socket path $objRedis->connect( ’127.0.0.1′, 6379, 2.5, NULL, 150 ); // Delay of 150 ms in-between reconnection attempts with a time out of 2.5 sec
2.get
根据key得到value
$redisClient -> get('key', 'value');
3.mget
根据key的队列获取多个value值
$arrKeys = array(“keyA”, “keyB”, “keyC”); $redisClient -> mget($arrKeys);
4.set
写入key-value对
$redisClient -> set('key');
5.setex
同样是写入key-value对,添加了过期时间
$redisClient -> setex('key', 3600, 'value' );
6.del
删除key
$redisClient -> del('key');
7.exists
判断key是否存在,如存在返回true
$redisClient -> exists('key');
8.close
关闭连接
$redisClient -> close();
(四)php使用redis的例子
通常redis作为数据库的cache而存在,这里我们可以看到redis是如何跟php+mysql整合的。
<?php
/* Functions for redis operations starts here */
$redisObj = new Redis();
function openRedisConnection( $hostName, $port){
global $redisObj;
// Opening a redis connection
$redisObj->connect( $hostName, $port );
return $redisObj;
}
function setValueWithTtl( $key, $value, $ttl ){
try{
global $redisObj;
// setting the value in redis
$redisObj->setex( $key, $ttl, $value );
}catch( Exception $e ){
echo $e->getMessage();
}
}
function getValueFromKey( $key ){
try{
global $redisObj;
// getting the value from redis
return $redisObj->get( $key);
}catch( Exception $e ){
echo $e->getMessage();
}
}
function deleteValueFromKey( $key ){
try{
global $redisObj;
// deleting the value from redis
$redisObj->del( $key);
}catch( Exception $e ){
echo $e->getMessage();
}
}
/* Functions for converting sql result object to array goes below */
function convertToArray( $result ){
$resultArray = array();
for( $count=0; $row = $result->fetch_assoc(); $count++ ) {
$resultArray[$count] = $row;
}
return $resultArray;
}
/* Functions for executing the mySql query goes below */
function executeQuery( $query ){
$mysqli = new mysqli( 'localhost', 'username', 'password', 'someDatabase' );
if( $mysqli->connect_errno ){
echo "Failed to connect to MySql:"."(".mysqli_connect_error().")".mysqli_connect_errno();
}
$result = $mysqli->query( $query );
// Calling function to convert result to array
$arrResult = convertToArray( $result );
return $arrResult;
}
$query = 'select * from sometable limit 1';
// Calling function to execute sql query
$arrValues = executeQuery( $query );
// Making json string
$jsonValue = json_encode($arrValues);
// Opening a redis connection
openRedisConnection( 'localhost', 6379 );
// Inserting the value with ttl = 1 hours
setValueWithTtl( 'somekey1', $jsonValue, 3600);
// Fetching value from redis using the key.
$val = getValueFromKey( 'somekey1' );
// Output: the json encoded array from redis
echo $val;
// Unsetting value from redis
deleteValueFromKey( $key );
?>
简单描述一下上面的phpredis例子,我们执行了一个sql语句从mysql中取数据,查询结果返回一个array集合,然后encode mysql查询出来的array成一个json格式插入到redis中,最后从redis中取出来,并做展现。

