redis 做數據庫緩存 php實現


<?php

    /*數據庫的表
            ( 'usr_id', 
            'name',
            'face_score', 
            'usr_sex',
            'usr_headimgurl'
    */
    $redis = new Redis();
    $redis->connect('127.0.0.1',6379);
    $usr_id ='2007';
        //方法例一
        //構造一個json字符串,存入redis,再讀出來, 這里的key是 'mykey' . $usr_id 拼成一個字符串
        $ret;
        $redis->set('mykey' . $usr_id,'[{"usr_id":"2007","name":"qipeng","usr_sex":"1","face_score":"1000","usr_headimgurl":"http://aaa"}]'); //注意key value是用的雙引號
        if($ret=$redis->get('mykey' . $usr_id))
        {
            //echo $ret;
            $row = json_decode($ret, true);
            
            $usr_id = $row[0]['usr_id'];
            $name = $row[0]['name'];
            $usr_sex = $row[0]['usr_sex'];
            $face_score = $row[0]['face_score'];
            $usr_headimgurl = stripslashes($row[0]['usr_headimgurl']);
        
            echo "\r\n               userID:$usr_id, wxName:$name, sex:$usr_sex, face_score:$face_score usr_headimgurl:$usr_headimgurl\n";
        }
        //方法例二
        //通過一個數組構造一個json字符串,存入redis,這里的這些值就可以是從數據庫讀出來的 

            $get_data[] = array( 'usr_id'=>'2007', 
            'name'=>'qipeng',
            'face_score'=>'1000', 
            'usr_sex'=>'1',
            'usr_headimgurl'=>'http://aaa'
        );
        $data = json_encode($get_data);                
        //echo $data;
        $redis->set('mykey' . $usr_id ,$data);
        if($ret=$redis->get('mykey' . $usr_id))
        {

            $row = json_decode($ret, true);
            //var_dump($row);

            $usr_id = $row[0]['usr_id'];
            $name = $row[0]['name'];
            $usr_sex = $row[0]['usr_sex'];
            $face_score = $row[0]['face_score'];
            $usr_headimgurl = stripslashes($row[0]['usr_headimgurl']);
        
            echo "\r\n               userID:$usr_id, wxName:$name, sex:$usr_sex, face_score:$face_score usr_headimgurl:$usr_headimgurl\n";
        }


?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM