php 加 redis 入門及簡單應用

來源:互聯網
上載者:User
本篇文章給大家分享的內容是php 加 redis 入門及簡單應用 ,有著一定的參考價值,有需要的朋友可以參考一下

一、實驗環境: win10 + redis3.2 + php7
二、php-redis / redis /redis圖形管理工個等安裝,此步驟略過;
三、redis常用的五種資料類型,不做詳細說明
參考:http://www.runoob.com/redis/r...
四、php + mysql + redis 簡單應用
資料庫名稱:redis 資料表:redis_user
類比 php 操作Mysql + redis 的 CURD 操作

1、config.php設定檔

<?php$config = array(    'mysql'=>array(        'host'=>'127.0.0.1',        'user'=>'root',        'pass'=>'root',        'dbname'=>'redis',        'prefix'=>'redis_'    ),    'redis'=>array(        'host'=>'127.0.0.1',        'port'=>6379    ));

index.php 入口檔案,操作Mysql時請使用主鍵ID

<?phpreqiure_once('Mysql.php');//增加資料// echo Mysql::getInstance()->table('user')->insert(['user'=>'張三','pass'=>md5('123456'),'create_time'=>date('Y-m-d H:i:s')]);//刪除資料// echo Mysql::getInstance()->table('user')->where(array('id'=>30))->delete();//查看單條資料// $data = Mysql::getInstance()->table('user')->where(array('id'=>'30'))->find();// print_r($data);//尋找所有資料// $all = Mysql::getInstance()->table('user')->field('id,user')->select();$all = Mysql::getInstance()->table('user')->select();print_r($all);//修改資料// echo Mysql::getInstance()->table('user')->where(array('id'=>30))->update(['user'=>'張三adfadfasdf11111111','pass'=>md5('123456aaa')]);?>



Mysql.php 資料庫以及redis操作檔案

<?phpclass Mysql{    static  $instance;    private $conn;    private $redis;    private $options = array();    //單例模式    private function __construct()    {        error_reporting(E_ALL^E_NOTICE^E_WARNING);        require_once(__DIR__.'/Config.php');        $conn = mysqli_connect($config['mysql']['host'],$config['mysql']['user'],$config['mysql']['pass'],$config['mysql']['dbname']);        if(mysqli_connect_errno($conn)) {            echo "串連Mysql失敗:".mysqli_connect_error();            exit;        }        mysqli_query($conn,'set names utf8');        $this->options['prefix'] = $config['mysql']['prefix'];        $this->conn = $conn;        $this->redis = new Redis();        $this->redis->connect($config['redis']['host'],$config['redis']['port']);    }    //擷取對象執行個體    static function getInstance()    {        if(self::$instance) {            return self::$instance;        } else {            self::$instance = new self();            return self::$instance;        }    }    //設定表名    public function table(string $table)    {        $this->options['table'] = '`'.$this->options['prefix'].$table.'`';        return $this;    }    //設定redis鍵名    public function redis(string $key)    {        $this->options['key'] = $key;        return $this;    }    //設定條件    public function where(array $where)    {        $condition = '';        $and = count($where) > 1 ? ' and ' : '';        foreach ($where as $key => $value) {            if($key == 'id') {$this->options['user_id'] = $value;}            if(strpos($key,':')) {                $arr = explode(':', $key);                $condition .= '`'.$arr['0'].'` '.$arr['1']. ' "'.$value.'" ' . $and ;             } else {                $condition .= '`'.$key.'` = ' .'"'.$value.'"' .$and  ;             }        }        $this->options['where'] = rtrim($condition,' and ');        return $this;    }    //設定欄位    public function field(string $field)    {        $this->options['field'] = $field;        return $this;    }        //增加資料    public function insert(array $data)    {        $key = '`'.implode('`,`', array_keys($data)).'`';        $value = '"'.implode('","', $data).'"';        $sql = "insert into {$this->options['table']} (".$key.") values (".$value.");";        if( mysqli_query($this->conn,$sql) ) {            $user_id = $this->conn->insert_id;            $data['id'] = $user_id;            //以hash類型儲存            $this->redis->hset($this->options['table'],$user_id,json_encode($data));            return $user_id;        } else {            return 0;        }    }    //刪除資料    public function delete()    {        $where = $this->options['where'] ? $this->options['where'] : '1';        $sql = "delete from {$this->options['table']} where {$where};";        if(mysqli_query($this->conn,$sql)) {            $this->redis->hdel($this->options['table'],$this->options['user_id']);            return 1;        } else {            return 0;        }    }    //修改資料    public function update(array $data)    {        $condition = '';        $where = $this->options['where'] ? $this->options['where'] : '1';        foreach ($data as $key => $value) {            $condition .= ", `".$key."` = '".$value."'";        }        $condition = substr($condition, 1);        $sql = " update {$this->options['table']} set {$condition} where {$where} ; ";        if(mysqli_query($this->conn,$sql)) {            $hashData = (array)json_decode($this->redis->hget($this->options['table'],$this->options['user_id']));            foreach ($data as $key => $value) {                $hashData[$key] = $value;            }            $this->redis->hset($this->options['table'],$this->options['user_id'],json_encode($hashData));            return 1;        } else {            return 0;        }    }    //尋找單條資料    public function find()    {        $field  = $this->options['field'] ? $this->options['field'] : '*';        $where = $this->options['where'] ? $this->options['where'] : '1';        if($this->options['user_id']) {            echo '從redis擷取資料<pre>';            $data = (array)json_decode($this->redis->hget($this->options['table'],$this->options['user_id']));            if($field != '*') {                $field = explode(',', $field);                foreach ($field as $value) {                    $arr[$value] = $data[$value];                    $arr['typ'] = 'redis';                }                return $arr;                            }            return $data;                    } else {                        $sql = " select {$field} from {$this->options['table']} where {$where}; ";            if($query = mysqli_query($this->conn,$sql)) {                return mysqli_fetch_assoc($query);            } else {                return array();            }        }    }    //尋找所有資料    public function select()    {        $data = array();        $field  = $this->options['field'] ? $this->options['field'] : '*';        $hashData = $this->redis->hgetall($this->options['table']);        if($hashData) {            if($field != '*') {                 $field = explode(',', $field);            }            foreach ($hashData as $key => $value) {                $data[$key] = array();                $values = (array)json_decode($value);                if($field != '*') {                    foreach ($field as $k => $v) {                        $data[$key][$v] = $values[$v];                    }                }else{                    $data[$key] = $values;                }            }            echo '從redis擷取資料<pre>';        } else {            $sql = " select {$field} from {$this->options['table']} ; ";            if($query = mysqli_query($this->conn,$sql)) {                while ($row = mysqli_fetch_assoc($query)) {                    $data[] = $row;                }            }        }        return $data;    }        public function __destruct()    {        mysqli_close($this->conn);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.