Redis (五 php与redis的结合使用)

编程入门 行业动态 更新时间:2024-10-11 21:26:47

<a href=https://www.elefans.com/category/jswz/34/1771249.html style=Redis (五 php与redis的结合使用)"/>

Redis (五 php与redis的结合使用)

1 安装phpredis扩展

(1)下载phpredis源码,hhtps://github/owlient/phpredis/downloads

(2)解压 tar -xzvf phpredis.tar.gz

(3)编译安装

        cd phpredis

        /usr/local/PHP/bin/phpize

        ./configure --with-php-config=config path(你的配置文件的路径)

        make

        make install

(4)修改php.ini

        添加 extension=Redis.so

        用phpinfo查看或者php -m | grep redis 查看redis扩展是否可用


(5)testCon.php 测试是否可以连接成功

    $redis = new Redis();$con = $redis->connect('127.0.0.1', 6379);$redis->set('key', 'val');$val = $redis->get('key');var_dump($val);$redis->close();
(6)实例分析
    发布微博是可能很多人同时操作,并发很多,单纯mysql可能会导致连接数过多,而使服务宕机,可以使用redis的list把消息放入队列,然后用cron定时刷新到mysql数据库,降低mysql的并发用到的文件:
redis.php 实现消息放入redis
weibo.php 实现消息获取,放入数据库
function.php 实现消息获取的模拟
内容如下:
1 redis.phpinclude_once 'function.php';$redis = new Redis();$redis->connect('127.0.0.1', 6379);$webInfo = array('uid' => get_uid(),'content' => get_content(),'timstamp' => time());$redis->lPush('weiboList', json_encode($webInfo));$redis->close();
2 function.phpfunction get_uid(){return rand(1, 1000);}//echo get_uid();function get_content(){return 'test - ' . getmygid() . rand(1, 10) . 'nj';}3 weibo.phpinclude_once "function.php";class weibo{private $host = '127.0.0.1';private $user = '...';private $pass = '...';private $db = 'test';private $table = 'weibo';//    实现发布微博的功能public function post(){echo $this->connect();}public function connect(){$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);if (!$con) {echo "mysql connect failed";echo "<br/>";echo "error no is :" . mysqli_errno();echo "<br/>";echo "error is :" . mysqli_error();echo "<br/>";}$uid = get_uid();$content = get_content();$sql = "insert into " . $this->table . "(uid,content) " . " values(" . $uid . ",'" . $content . "')";$res = mysqli_query($con, $sql);if (!$res) {return 'pub failed';}return 'pub success';}}

更多推荐

Redis (五 php与redis的结合使用)

本文发布于:2024-02-11 06:50:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1679705.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Redis   php   redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!