版权声明:本文为博主原创文章,未经博主允许不得转载。
1 安装phpredis扩展
(1)下载phpredis源码,hhtps://github.com/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.php include_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.php function get_uid() { return rand(1, 1000); } //echo get_uid(); function get_content() { return 'test - ' . getmygid() . rand(1, 10) . 'nj'; } 3 weibo.php include_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'; } }