Hướng dẫn cài đặt redis và memcache trên cent os 7 ,đồng thời cấu hình lưu biến session ecshop trên đó

0
138

1. Hướng dẫn cài đặt Redis

Để Redis có thể làm việc được với Magento, chúng ta sẽ cần cài đặt Redis server cùng với extension PhpRedis để PHP có thể kết nối được với Redis.
– Thêm repo epel, remi
## CentOS 7 ##
yum install epel-release
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm

## CentOS 6 ##
yum install epel-release
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
– Cài đặt Redis và PhpRedis extension
## PHP 7.2 ##
 yum --enablerepo=remi,remi-php72 install redis php-pecl-redis service 
php-fpm restart
## PHP 7.1 ##
yum --enablerepo=remi,remi-php71 install redis php-pecl-redis
service php-fpm restart

## PHP 7.0 ##
yum --enablerepo=remi,remi-php70 install redis php-pecl-redis
service php-fpm restart

## PHP 5.6 ##
yum --enablerepo=remi,remi-php56 install redis php-pecl-redis
service php-fpm restart

## PHP 5.5 ##
yum --enablerepo=remi,remi-php55 install redis php-pecl-redis
service php-fpm restart
– Chạy Redis và tự động khởi động khi boot
chkconfig redis on
service redis start

2. Kiểm tra lại quá trình cài đặt Redis

– Check lại Redis server
redis-cli ping
Nếu kết quả về PONG là ok
– Check lại PhpRedis extension
php -m | grep redis
Kết quả trả về redis là ok
– Redis shell tools
Mặc định Redis cài đặt với một công cụ comment là redis-cli
Sau khi khởi động Redis, các bạn có thể sử dụng một số command như:
  • FLUSHALL – clear all databases
  • SELECT # – select database under index #
  • FLUSHDB – empty currently selected database
  • KEYS * – list all keys from currently selected

3. PHPRedMin – Quản lý và theo dõi Redis

curl -s http://getcomposer.org/installer | php
php composer.phar create-project -s dev erik-dubbelboer/php-redis-admin /home/admin/web/vesta.example.com/public_html/phpredmin
Sau khi cài xong, bạn có thể sử dụng PHPRedMin để quản lý Redis với giao diện web trực quan ngay. Tải về tại PHPRedMin Github.

Cài đặt Memcached và sử dụng cho WordPress

Đối với CentOS/RHEL

yum install --enablerepo=remi php-pecl-memcache memcached libmemcached -y

Đối với Ubuntu/Debian

apt-get install memcached php5-memcache

Khởi động Memcached

service memcached start

Tự khởi động memcached khi boot (dành cho CentOS)

chkconfig memcached on

Sau đó là khởi động lại Apache.

Với CentOS/RHEL

service httpd restart

Với Ubuntu/Debian

service apache2 restart

Cache session ecshop : Khi web có nhiều người truy cập mà cứ insert liên tục vào mysql sẽ rất chậm và phình to cơ sở dữ liệu .Nên mình lưu sang memcache hoặc redis cho giảm tải

cls_redis_session.php

<?php

    /**
    * ecshop SESSION 保存类
    * ============================================================================
    * 浣跨敤锛涗笉鍏佽?瀵圭▼搴忎唬鐮佷互浠讳綍褰㈠紡浠讳綍鐩?殑鐨勫啀鍙戝竷銆
    * ============================================================================
    * $Author: liubo $
    * $Id: cls_session.php 17217 2011-01-19 06:29:08Z liubo $
    */

    if (!defined('IN_ECTOUCH'))
    {
    die('Hacking attempt');
    }

    class cls_session
    {
        var $db = NULL;
        var $session_table = '';
        var $max_life_time = 86400; // SESSION 保存时间
        var $session_name = '';
        var $session_id = '';
        var $session_expiry = '';
        var $session_md5 = '';
        var $session_cookie_path = '/';
        var $session_cookie_domain = '';
        var $session_cookie_secure = false;
        var $redis='';
        var $_ip = '';
        var $_time = 0;

        function __construct(&$db, $session_table, $session_data_table, $session_name = 'ECS_ID', $session_id = '')
        {
            $this->cls_session($db, $session_table, $session_data_table, $session_name, $session_id);
        }

        function cls_session(&$db, $session_table, $session_data_table, $session_name = 'ECS_ID', $session_id = '')
        {
            $this->redis = new Redis();
            $this->redis->connect('127.0.0.1', 6379);
            $GLOBALS['_SESSION'] = array();

            if (!empty($GLOBALS['cookie_path']))
            {
                    $this->session_cookie_path = $GLOBALS['cookie_path'];
            }
            else
            {
                $this->session_cookie_path = '/';
            }

            if (!empty($GLOBALS['cookie_domain']))
            {
                $this->session_cookie_domain = $GLOBALS['cookie_domain'];
            }
            else
            {
                $this->session_cookie_domain = '';
            }

            if (!empty($GLOBALS['cookie_secure']))
            {
                $this->session_cookie_secure = $GLOBALS['cookie_secure'];
            }
            else
            {
                $this->session_cookie_secure = false;
            }

            $this->session_name = $session_name;
            $this->session_table = $session_table;
            $this->session_data_table = $session_data_table;

            $this->db = &$db;
            //$this->_ip = real_ip();以下代码解决登陆问题
            if(isset($_COOKIE['real_ipd']) && !empty($_COOKIE['real_ipd']))
            {
                $this->_ip = $_COOKIE['real_ipd'];
            }
            else
            {
                $this->_ip = real_ip();
                setcookie("real_ipd", $this->_ip, time()+36000, $this->session_cookie_path);
            }

            if ($session_id == '' && !empty($_COOKIE[$this->session_name]))
            {
                $this->session_id = $_COOKIE[$this->session_name];
            }
            else
            {
                $this->session_id = $session_id;
            }
            if ($this->session_id)
            {
                $tmp_session_id = substr($this->session_id, 0, 32);
                if ($this->gen_session_key($tmp_session_id) == substr($this->session_id, 32))
                {
                    $this->session_id = $tmp_session_id;
                }
                else
                {
                    $this->session_id = '';
                }
            }

            $this->_time = time();

            if ($this->session_id)
            {
                $this->load_session();
            }
            else
            {
                $this->gen_session_id();

                setcookie($this->session_name, $this->session_id . $this->gen_session_key($this->session_id), 0, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure);
            }
            register_shutdown_function(array(&$this, 'close_session'));
        }

        function gen_session_id()
            {
                $this->session_id = md5(uniqid(mt_rand(), true));

                return $this->insert_session();
            }

            function gen_session_key($session_id)
            {
            static $ip = '';

            if ($ip == '')
            {
            $ip = substr($this->_ip, 0, strrpos($this->_ip, '.'));
            }

            return sprintf('%08x', crc32(ROOT_PATH . $ip . $session_id));
            }

            function insert_session()
            {
            $sess_array=array();
            //$sess_array["expiry"]=$this->_time;
            $sess_array["ip"]=$this->_ip;
            $sess_array["data"]='a:0:{}';
            $sess=serialize($sess_array);
            $return=$this->redis->set($this->session_id, $sess);
            $this->redis->expire($this->session_id,$max_life_time);
            return $return;
            // return $this->db->query('INSERT INTO ' . $this->session_table . " (sesskey, expiry, ip, data) VALUES ('" . $this->session_id . "', '". $this->_time ."', '". $this->_ip ."', 'a:0:{}')");
            }

            function load_session()
            {
            // $session = $this->db->getRow('SELECT userid, adminid, user_name, user_rank, discount, email, data, expiry FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "'");
            $session=$this->redis->get($this->session_id);
            if ($session)
            {
            $this->insert_session();

            $this->session_expiry = 0;
            $this->session_md5 = '40cd750bba9870f18aada2478b24840a';
            $GLOBALS['_SESSION'] = array();
            }
            else
            {
            $session=unserialize($session);
            if (!empty($session['data']))
            {
            $this->session_expiry =$this->max_life_time;
            $this->redis->expire($this->session_id,$max_life_time);
            $this->session_md5 = md5($session['data']);
            $GLOBALS['_SESSION'] = unserialize($session['data']);
            $GLOBALS['_SESSION']['user_id'] = $session['userid'];
            $GLOBALS['_SESSION']['admin_id'] = $session['adminid'];
            $GLOBALS['_SESSION']['user_name'] = $session['user_name'];
            $GLOBALS['_SESSION']['user_rank'] = $session['user_rank'];
            $GLOBALS['_SESSION']['discount'] = $session['discount'];
            $GLOBALS['_SESSION']['email'] = $session['email'];
            }

            }
            }

            function update_session()
            {
            $adminid = !empty($GLOBALS['_SESSION']['admin_id']) ? intval($GLOBALS['_SESSION']['admin_id']) : 0;
            $userid = !empty($GLOBALS['_SESSION']['user_id']) ? intval($GLOBALS['_SESSION']['user_id']) : 0;
            $user_name = !empty($GLOBALS['_SESSION']['user_name']) ? trim($GLOBALS['_SESSION']['user_name']) : 0;
            $user_rank = !empty($GLOBALS['_SESSION']['user_rank']) ? intval($GLOBALS['_SESSION']['user_rank']) : 0;
            $discount = !empty($GLOBALS['_SESSION']['discount']) ? round($GLOBALS['_SESSION']['discount'], 2) : 0;
            $email = !empty($GLOBALS['_SESSION']['email']) ? trim($GLOBALS['_SESSION']['email']) : 0;
            unset($GLOBALS['_SESSION']['admin_id']);
            unset($GLOBALS['_SESSION']['user_id']);
            unset($GLOBALS['_SESSION']['user_name']);
            unset($GLOBALS['_SESSION']['user_rank']);
            unset($GLOBALS['_SESSION']['discount']);
            unset($GLOBALS['_SESSION']['email']);

            $data = serialize($GLOBALS['_SESSION']);
            // $this->_time = time();

            // if ($this->session_md5 == md5($data) && $this->_time < $this->session_expiry + 10)
            // {
            // return true;
            // }

            $data = addslashes($data);

            // if (isset($data{255}))
            // {
            // $this->db->autoReplace($this->session_data_table, array('sesskey' => $this->session_id, 'expiry' => $this->_time, 'data' => $data), array('expiry' => $this->_time,'data' => $data));

            // $data = '';
            // }
            $sess=array();
            //$sess["expiry"]=$this->_time;
            $sess["ip"]=$this->_ip;
            $sess["userid"]=$userid;
            $sess["user_name"]=$user_name;
            $sess["user_rank"]=$user_rank;
            $sess["discount"]=$discount;
            $sess["email"]=$email;
            $sess["data"]=$data;
            $session=serialize($sess);
            $return=$this->redis->set($this->session_id, $session);
            $this->redis->expire($this->session_id,$this->max_life_time);
            return $return;
            // return $this->db->query('UPDATE ' . $this->session_table . " SET expiry = '" . $this->_time . "', ip = '" . $this->_ip . "', userid = '" . $userid . "', adminid = '" . $adminid . "', user_name='" . $user_name . "', user_rank='" . $user_rank . "', discount='" . $discount . "', email='" . $email . "', data = '$data' WHERE sesskey = '" . $this->session_id . "' LIMIT 1");
            }

            function close_session()
            {
            $this->update_session();

            /* 闅忔満瀵 sessions_data 鐨勫簱杩涜?鍒犻櫎鎿嶄綔 */
            // if (mt_rand(0, 2) == 2)
            // {
            // $this->db->query('DELETE FROM ' . $this->session_data_table . ' WHERE expiry < ' . ($this->_time - $this->max_life_time));
            // }

            // if ((time() % 2) == 0)
            // {
            // return $this->redis->del()
            // // return $this->db->query('DELETE FROM ' . $this->session_table . ' WHERE expiry < ' . ($this->_time - $this->max_life_time));
            // }

            return true;
            }

            function delete_spec_admin_session($adminid)
            {
            // if (!empty($GLOBALS['_SESSION']['admin_id']) && $adminid)
            // {
            // return $this->db->query('DELETE FROM ' . $this->session_table . " WHERE adminid = '$adminid'");
            // }
            // else
            // {
            return true;
            // }
            }

            function destroy_session()
            {
            $GLOBALS['_SESSION'] = array();

            setcookie($this->session_name, $this->session_id, 1, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure);

            /* weifenxiao 删除购物车 */
            if (!empty($GLOBALS['ecs']))
            {
            $this->db->query('DELETE FROM ' . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '$this->session_id'");
            }
            /* weifenxiao 鑷?畾涔夋墽琛岄儴鍒 */

            // $this->db->query('DELETE FROM ' . $this->session_data_table . " WHERE sesskey = '" . $this->session_id . "' LIMIT 1");
            if (!$this->redis->exists($this->session_id)) {
            return true;
            }
            return $this->redis->del($this->session_id);
            // return $this->db->query('DELETE FROM ' . $this->session_table . " WHERE sesskey = '" . $this->session_id . "' LIMIT 1");
            }

            function get_session_id()
            {
            return $this->session_id;
            }

            function get_users_count()
            {
            return count($this->redis->key("*"));
        }
    }

?>

Và file cls_mem_session.php

<?php
 
if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}
 
/*------------------------------------------------------ */
//-- 该类用于将SESSION直接写入Memcache
/*------------------------------------------------------ */
class cls_session
{
    var $db             = NULL;
 
    var $max_life_time  = 86400; // SESSION 过期时间
 
    var $session_name   = '';
    var $session_id     = '';
 
    var $session_expiry = '';
    var $session_md5    = '';
 
    var $session_cookie_path   = '/';
    var $session_cookie_domain = '';
    var $session_cookie_secure = false;
 
    var $_ip   = '';
    var $_time = 0;
 
    function __construct(&$db, $session_table, $session_data_table, $session_name = 'ECS_ID', $session_id = '')
    {
        $m = new Memcache;
        $m->addServer('127.0.0.1', 11211);
        $this->cls_session($m, $session_name, $session_id);
    }
 
    function cls_session(&$db, $session_name = 'ECS_ID', $session_id = '')
    {
        $GLOBALS['_SESSION'] = array();
 
        if (!empty($GLOBALS['cookie_path']))
        {
            $this->session_cookie_path = $GLOBALS['cookie_path'];
        }
        else
        {
            $this->session_cookie_path = '/';
        }
 
        if (!empty($GLOBALS['cookie_domain']))
        {
            $this->session_cookie_domain = $GLOBALS['cookie_domain'];
        }
        else
        {
            $this->session_cookie_domain = '';
        }
 
        if (!empty($GLOBALS['cookie_secure']))
        {
            $this->session_cookie_secure = $GLOBALS['cookie_secure'];
        }
        else
        {
            $this->session_cookie_secure = false;
        }
      
        $this->session_name       = $session_name;
 
        $this->db  = &$db;
        $this->_ip = real_ip();
 
        if ($session_id == '' && !empty($_COOKIE[$this->session_name]))
        {
            $this->session_id = $_COOKIE[$this->session_name];
        }
        else
        {
            $this->session_id = $session_id;
        }
 
        if ($this->session_id)
        {
            $tmp_session_id = substr($this->session_id, 0, 32);
            if ($this->gen_session_key($tmp_session_id) == substr($this->session_id, 32))
            {
                $this->session_id = $tmp_session_id;
            }
            else
            {
                $this->session_id = '';
            }
        }
 
        $this->_time = time();
 
        if ($this->session_id)
        {
            $this->load_session();
        }
        else
        {
            $this->gen_session_id();
            setcookie($this->session_name, $this->session_id . $this->gen_session_key($this->session_id), 0, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure);
        }
        register_shutdown_function(array(&$this, 'close_session'));
    }
 
    function gen_session_id()
    {
        $this->session_id = md5(uniqid(mt_rand(), true));
 
        return $this->insert_session();
    }
 
    function gen_session_key($session_id)
    {
        static $ip = '';
 
        if ($ip == '')
        {
            $ip = substr($this->_ip, 0, strrpos($this->_ip, '.'));
        }
 
        return sprintf('%08x', crc32(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] . ROOT_PATH . $ip . $session_id : ROOT_PATH . $ip . $session_id));
    }
 
    function insert_session()
    {
        return $this->db->set($this->session_id, array('expiry'=>$this->_time, 'ip'=>$this->_ip, 'data'=>'a:0:{}'), false, $this->max_life_time);
    }
 
    function load_session()
    {
        $session = $this->db->get($this->session_id);
        if (empty($session))
        {
            $this->insert_session();
            $this->session_expiry = 0;
            $this->session_md5 = '40cd750bba9870f18aada2478b24840a';
            $GLOBALS['_SESSION'] = array();
        }
        else
        {
            if (!empty($session['data']) && $this->_time - $session['expiry'] <= $this->max_life_time)
            {
                $this->session_expiry = $session['expiry'];
                $this->session_md5 = md5($session['data']);
                $GLOBALS['_SESSION']  = unserialize(stripslashes($session['data']));
            }
            else
            {
                $this->session_expiry = 0;
                $this->session_md5 = '40cd750bba9870f18aada2478b24840a';
                $GLOBALS['_SESSION']  = array();
            }
        }
    }
 
    function update_session()
    {
        $adminid = !empty($GLOBALS['_SESSION']['admin_id']) ? intval($GLOBALS['_SESSION']['admin_id']) : 0;
        $userid  = !empty($GLOBALS['_SESSION']['user_id'])  ? intval($GLOBALS['_SESSION']['user_id'])  : 0;
 
        $data = serialize($GLOBALS['_SESSION']);
        $this->_time = time();
 
        if ($this->session_md5 == md5($data) && $this->_time < $this->session_expiry + 10)
        {
            return true;
        }
 
        $data = addslashes($data);
 
        return $this->db->replace($this->session_id, array('expiry'=>$this->_time, 'ip'=>$this->_ip, 'userid'=>$userid, 'adminid'=>$adminid, 'data'=>$data), false, $this->max_life_time);
    }
 
    function close_session()
    {
        $this->update_session();
        return true;
    }
 
    function delete_spec_admin_session($adminid)
    {
        if (!empty($GLOBALS['_SESSION']['admin_id']) && $adminid)
        {
            $all_items = $this->db->getExtendedStats('items');
            $items = $all_items['127.0.0.1:11211']['items'];
            foreach ($items as $key => $item) {
                if (isset($item['adminid'])) {
                    if ($item['adminid'] == $adminid) return $this->db->delete($key);
                }
            }
        }
        else
        {
            return false;
        }
    }
 
    function destroy_session()
    {    
        $GLOBALS['_SESSION'] = array();
 
        setcookie($this->session_name, $this->session_id, 1, $this->session_cookie_path, $this->session_cookie_domain, $this->session_cookie_secure);
 
        /* ECSHOP 自定义执行部分 */
        if (!empty($GLOBALS['ecs']))
        {
            $GLOBALS['db']->query('DELETE FROM ' . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '$this->session_id'");
        }
        /* ECSHOP 自定义执行部分 */
 
        return $this->db->delete($this->session_id);
    }
 
    function get_session_id()
    {
        return $this->session_id;
    }
 
    function get_users_count()
    {
        $all_items = $this->db->getExtendedStats();
        return $count = $all_items['127.0.0.1:11211']['curr_items'];//由于有其他key的缓存,因此这只是个接近数值
    }
 
}
 
?>

File init.php

if (!defined('INIT_NO_USERS'))
{

    
    	/* 初始化session */
    	include(ROOT_PATH . 'includes/cls_session.php');
    $sess = new cls_session($db, $ecs->table('sessions'), $ecs->table('sessions_data'));
    // chọn chế độ session cache có lợi cho mình
    
    /* 添加redis支持 */
    if (isset($session_type) && $session_type == "mem")
    {
        include(ROOT_PATH . 'include/cls_mem_session.php');
    }
    elseif (isset($session_type) && $session_type == "redis")
    {
        include(ROOT_PATH . 'include/cls_redis_session.php');
    }
    else{ 
        include(ROOT_PATH . 'include/cls_session.php');
    }
    $sess = new cls_session($db, $ecs->table('sessions'), $ecs->table('sessions_data'));
    
   
    define('SESS_ID', $sess->get_session_id());
}