Redis - PHP



在你的 PHP 程序中开始使用 Redis 之前,你需要确保在计算机上设置了 Redis PHP 驱动程序和 PHP。你可以在 PHP 教程中查看如何在你的计算机上安装 PHP。

安装

现在,让我们来检查如何设置 Redis PHP 驱动程序。

你需要从 github 存储库 https://github.com/nicolasff/phpredis 下载 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 
广告