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:bash;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</pre><p>修改php.ini文件</p><pre class="brush:bash;toolbar:false">vi/usr/local/php/lib/php.ini</pre><p>增加如下内容:</p><pre class="brush:bash;toolbar:false">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><img src="/up_pic/201805/281010488138.jpg" title="281010488138.jpg" alt="1.jpg"/></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;</pre><p>执行脚本,输出结果为:</p><p>Connection to server sucessfully</p><p>Server is running: PONG</p><p>Redis PHP String(字符串) 实例</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;; //设置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><p>Connection to server sucessfully</p><p>Stored string in redis:: Redis tutorial</p><p>Redis PHP List(列表) 实例</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;; //存储数据到列表中 $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><p>Connection to server sucessfully</p><p>Stored string in redis</p><p>Mysql</p><p>Mongodb</p><p>Redis</p><p>Redis PHP Keys 实例</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;; //获取数据并输出 $arList=$redis-&gt;keys(&quot;*&quot;); echo&quot;Storedkeysinredis::&quot;; print_r($arList); ?&gt;</pre><p>执行脚本,输出结果为:</p><p>Connection to server sucessfully</p><p>Stored string in redis::</p><p>tutorial-name</p><p>tutorial-list</p>
RangeTime:0.008334s
RangeMem:207.51 KB
返回顶部 留言