本文我们主要和大家分享PHP使用Redis实例详解,希望能帮助到大家。
开始在PHP中使用Redis前,我们需要确保已经安装了redis服务和PHP redis驱动,且你的机器上能正常使用PHP。接下来让我们安装PHP redis驱动:下载地址为:https://github.com/phpredis/phpredis/releases。
PHP安装redis扩展
以下操作需要在下载的phpredis目录中完成:
1 2 | $ wget https:
$ make && make install
|
Salin selepas log masuk
修改php.ini文件
1 | vi /usr/local/php/lib/php.ini
|
Salin selepas log masuk
增加如下内容;
1 | extension_dir = "/usr/local/php/lib/php/extensions/no-debug-zts-20090626" extension=redis.so
|
Salin selepas log masuk
安装完成后重启php-fpm或apache。查看phpinfo信息,就能看到redis扩展。

连接到redis服务
1 2 3 4 5 6 7 8 | <?php
$redis = new Redis();
$redis ->connect( '127.0.0.1' , 6379);
echo "Connection to server sucessfully" ;
echo "Server is running: " . $redis ->ping();
?>
|
Salin selepas log masuk
执行脚本,输出结果为:
1 | Connection to server sucessfullyServer is running: PONG
|
Salin selepas log masuk
Redis PHP String(字符串)实例
1 2 3 4 5 6 7 8 9 10 | <?php
$redis = new Redis();
$redis ->connect( '127.0.0.1' , 6379);
echo "Connection to server sucessfully" ;
$redis ->set( "tutorial-name" , "Redis tutorial" );
echo "Stored string in redis:: " . $redis ->get( "tutorial-name" );
?>
|
Salin selepas log masuk
执行脚本,输出结果为:
1 | Connection to server sucessfullyStored string in redis:: Redis tutorial
|
Salin selepas log masuk
Redis PHP List(列表)实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php
$redis = new Redis();
$redis ->connect( '127.0.0.1' , 6379);
echo "Connection to server sucessfully" ;
$redis ->lpush( "tutorial-list" , "Redis" );
$redis ->lpush( "tutorial-list" , "Mongodb" );
$redis ->lpush( "tutorial-list" , "Mysql" );
$arList = $redis ->lrange( "tutorial-list" , 0 ,5);
echo "Stored string in redis" ;
print_r( $arList );
?>
|
Salin selepas log masuk
执行脚本,输出结果为:
1 | Connection to server sucessfullyStored string in redisMysqlMongodbRedis
|
Salin selepas log masuk
Redis PHP Keys 实例
1 2 3 4 5 6 7 8 9 10 | <?php
$redis = new Redis();
$redis ->connect( '127.0.0.1' , 6379);
echo "Connection to server sucessfully" ;
$arList = $redis ->keys( "*" );
echo "Stored keys in redis:: " ;
print_r( $arList );
?>
|
Salin selepas log masuk
执行脚本,输出结果为:
1 2 | Connection to server sucessfullyStored string in redis::tutorial-name
tutorial-list
|
Salin selepas log masuk
相关推荐:
详解PHP使用redis队列实现电商订单自动确认收货
PHP项目中需要用到Redis的场景
PHP之Redis扩展从安装到使用
Atas ialah kandungan terperinci PHP使用Redis实例详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!