Redis 专题
您的位置:database > Redis专题 > PHP连接Redis
PHP连接Redis
作者:--    发布时间:2019-11-20

在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安装完成!

使用连接到redis服务器

<?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

redis php字符串示例

<?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

redis php列表示例

<?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

redis php键示例

<?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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册