在 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 installShell
现在,将 "modules" 文件夹的内容复制并粘贴到 PHP 扩展目录中,并在 php.ini 中添加以下行。
- extension = redis.soShell
现在,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(); ?>PHP
当程序执行时,将产生以下结果。
- Connection to server sucessfully
- Server is running: PONGShell
- <?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"); ?>PHP
执行上面代码,将生成以下结果 -
- Connection to server sucessfully
- Stored string in redis:: Redis tutorialJava
- <?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); ?>PHP
执行上面代码,将生成以下结果 -
- Connection to server sucessfully
- Stored string in redis:: Redis
- Mongodb
- MysqlPHP
- <?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); ?>PHP
执行上面代码,将生成以下结果 -
- Connection to server sucessfully
- Stored string in redis:: tutorial-name
- tutorial-list
来源: