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


?>
相關文章
相關標籤/搜索