在php程序中使用redis之前,需要确保在机器上安装了redis的php驱动程序和php环境。可以先在将php电脑上并配置好环境。
现在,让我们看看如何设置redis php驱动程序。
从github库下载phpredis
=> http://github.com/nicolasff/phpredis。 当下载它之后,提取文件到phpredis
目录。在ubuntu上,安装以下扩展。
cd phpredis
sudo phpize
sudo ./configure
sudo make
sudo make install
现在,将“modules
”文件夹的内容复制并粘贴到php扩展目录中,并在php.ini
中添加以下行。
extension = redis.so
现在,redis php安装完成!
<?php
//connecting to redis server on localhost
$redis = new redis();
$redis->connect('127.0.0.1', 6379);
echo "connection to server sucessfully";
//check whether server is running or not
echo "server is running: ".$redis->ping();
?>
当程序执行时,将产生以下结果。
connection to server sucessfully
server is running: pong
<?php
//connecting to redis server on localhost
$redis = new redis();
$redis->connect('127.0.0.1', 6379);
echo "connection to server sucessfully";
//set the data in redis string
$redis->set("tutorial-name", "redis tutorial");
// get the stored data and print it
echo "stored string in redis:: " .$redis→get("tutorial-name");
?>
执行上面代码,将生成以下结果 -
connection to server sucessfully
stored string in redis:: redis tutorial
<?php
//connecting to redis server on localhost
$redis = new redis();
$redis->connect('127.0.0.1', 6379);
echo "connection to server sucessfully";
//store data in redis list
$redis->lpush("tutorial-list", "redis");
$redis->lpush("tutorial-list", "mongodb");
$redis->lpush("tutorial-list", "mysql");
// get the stored data and print it
$arlist = $redis->lrange("tutorial-list", 0 ,5);
echo "stored string in redis:: ";
print_r($arlist);
?>
执行上面代码,将生成以下结果 -
connection to server sucessfully
stored string in redis::
redis
mongodb
mysql
<?php
//connecting to redis server on localhost
$redis = new redis();
$redis->connect('127.0.0.1', 6379);
echo "connection to server sucessfully";
// get the stored keys and print it
$arlist = $redis->keys("*");
echo "stored keys in redis:: "
print_r($arlist);
?>
执行上面代码,将生成以下结果 -
connection to server sucessfully
stored string in redis::
tutorial-name
tutorial-list