redis 做数据库缓存 php实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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";
        }


?>

 

以上是关于redis 做数据库缓存 php实现的主要内容,如果未能解决你的问题,请参考以下文章

PHP + Redis 实现消息队列

PHP使用Redis实现消息队列

php redis做mysql的缓存,怎么异步redis同步到mysql数据库?

LAMP+Redis缓存数据库整合

redis常见使用场景下PHP实现

redis怎么做消息队列