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


?>

 

posted on 2017-09-21 16:57  你又来骗我  阅读(5693)  评论(0编辑  收藏  举报

导航