PHP 使用 Redis

<p>安装</p><p>开始在 PHP 中使用 Redis 前, 我们需要确保已经安装了 redis 服务及 PHP redis 驱动,且你的机器上能正常使用 PHP。 接下来让我们安装 PHP redis 驱动:下载地址为:https://github.com/phpredis/phpredis/releases。</p><p>PHP安装redis扩展</p><p>以下操作需要在下载的 phpredis 目录中完成:</p><pre class="brush:php;toolbar:false">$wgethttps://github.com/phpredis/phpredis/archive/3.1.4.tar.gz $cdphpredis-3.1.4#进入phpredis目录 $/usr/local/php/bin/phpize#php安装后的路径 $./configure--with-php-config=/usr/local/php/bin/php-config $make&amp;&amp;makeinstall 修改php.ini文件 vi/usr/local/php/lib/php.ini 增加如下内容: extension_dir=&quot;/usr/local/php/lib/php/extensions/no-debug-zts-20090626&quot; extension=redis.so</pre><p>安装完成后重启php-fpm 或 apache。查看phpinfo信息,就能看到redis扩展。</p><p>PHP 使用 Redis</p><p>连接到 redis 服务</p><pre class="brush:php;toolbar:false">&lt;?php //连接本地的Redis服务 $redis=newRedis(); $redis-&gt;connect(&#39;127.0.0.1&#39;,6379); echo&quot;Connectiontoserversucessfully&quot;; //查看服务是否运行 echo&quot;Serverisrunning:&quot;.$redis-&gt;ping(); ?&gt; 执行脚本,输出结果为: Connectiontoserversucessfully Serverisrunning:PONG RedisPHPString(字符串)实例 &lt;?php //连接本地的Redis服务 $redis=newRedis(); $redis-&gt;connect(&#39;127.0.0.1&#39;,6379); echo&quot;Connectiontoserversucessfully&quot;; //设置redis字符串数据 $redis-&gt;set(&quot;tutorial-name&quot;,&quot;Redistutorial&quot;); //获取存储的数据并输出 echo&quot;Storedstringinredis::&quot;.$redis-&gt;get(&quot;tutorial-name&quot;); ?&gt;</pre><p>执行脚本,输出结果为:</p><pre class="brush:php;toolbar:false">Connectiontoserversucessfully Storedstringinredis::Redistutorial RedisPHPList(列表)实例 &lt;?php //连接本地的Redis服务 $redis=newRedis(); $redis-&gt;connect(&#39;127.0.0.1&#39;,6379); echo&quot;Connectiontoserversucessfully&quot;; //存储数据到列表中 $redis-&gt;lpush(&quot;tutorial-list&quot;,&quot;Redis&quot;); $redis-&gt;lpush(&quot;tutorial-list&quot;,&quot;Mongodb&quot;); $redis-&gt;lpush(&quot;tutorial-list&quot;,&quot;Mysql&quot;); //获取存储的数据并输出 $arList=$redis-&gt;lrange(&quot;tutorial-list&quot;,0,5); echo&quot;Storedstringinredis&quot;; print_r($arList); ?&gt;</pre><p>执行脚本,输出结果为:</p><pre class="brush:php;toolbar:false">Connectiontoserversucessfully Storedstringinredis Mysql Mongodb Redis RedisPHPKeys实例 &lt;?php //连接本地的Redis服务 $redis=newRedis(); $redis-&gt;connect(&#39;127.0.0.1&#39;,6379); echo&quot;Connectiontoserversucessfully&quot;; //获取数据并输出 $arList=$redis-&gt;keys(&quot;*&quot;); echo&quot;Storedkeysinredis::&quot;; print_r($arList); ?&gt; 执行脚本,输出结果为: Connectiontoserversucessfully Storedstringinredis:: tutorial-name tutorial-list</pre>
RangeTime:0.007004s
RangeMem:206.59 KB
返回顶部 留言