1. 程式人生 > >Redis (五 php與redis的結合使用)

Redis (五 php與redis的結合使用)

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';
        }
    }