Yii2使用Redis - 從安裝redis到使用 [ 2.0 版本 ]

1、安裝Redis和簡單配置

1. 下載Redis安裝包

wget http://download.redis.io/releases/redis-3.0.5.tar.gz

2. 安裝Redis

tar xzf redis-3.0.5.tar.gz
cd redis-3.0.5
make

3. 啓動Redis

./src/redis-server &

附加內容 :

  • Redis默認不是後臺啓動,不加 「&」 時會一直停留在命令界面
    • 最好搭配配置文件一塊兒啓動例如:
./src/redis-server ./redis.conf
  • redis.conf中設置 「daemonize no」 爲 「daemonize yes」 也表明redis之後臺的方式啓動,前提時redis-server啓動時帶上redis.conf

2、安裝phpredis擴展

1. 下載phpredis擴展安裝包

wget http://pecl.php.net/get/redis-2.2.7.tgz , 本文選擇2.2.7版本

2. 安裝phpredis

tar zxvf redis-2.2.7.tgz
cd redis-2.2.7
/opt/server/php-5.5.7/bin/phpize
./configure
make
make install
  • 以上步驟完成後須要在php.ini中添加以下代碼:
extension=/opt/server/php-5.5.7/lib/php/extensions/no-debug-non-zts-20121212/redis.so

3.重啓web組件(本文使用Nginx + php5-fpm)

/opt/server/nginx/sbin/nginx -s reload
kill -USR2 `cat /opt/server/php-5.5.7/var/run/php-fpm.pid`

3、配置Yii2的redis擴展(本文使用Yii2 basic 版)

cd /www/html/basic php composer.phar require --prefer-dist yiisoft/yii2-redis

2. 配置basic/config/web.php

在components數組中添加以下內容:php

'redis' => [
    'class' => 'yii\redis\Connection',
    'hostname' => 'localhost',
    'port' => 6379,
    'database' => 0,
],

3. 使用

$redis = Yii::$app->redis;
$redis->get('key');
$redis->set('k','v');

附加(一些報錯解決)

basic/vendor/yiisoft/yii2-redis/Connection.php文件的源碼中265行開始(因實際而定)css

  • 變量 errorNumber 、errorDescription ,沒提早定義Yii2 一直報undefinedhtml

  • "@"把報錯屏蔽了,一直查不到緣由,刪掉"@"才發現stream_socket_client、stream_socket_server()這兩個函數禁用了nginx

更改前git

$this->_socket = @stream_socket_client( 
            $this->unixSocket ? 'unix://' . $this->unixSocket : 'tcp://' . $this->hostname . ':' . $this->port,
            $errorNumber,      
            $errorDescription,
            $this->connectionTimeout ? $this->connectionTimeout : ini_get("default_socket_timeout")
);

更改後github

//也能夠不定義這兩個變量,一般項目都會忽略notice報錯,視實際狀況而定
$errorNumber = '';
$errorDescription = '';
//----若是報錯:Warning:stream_socket_server() has been disabled for security reasons... 請看下面解決方法
//----這裏"@" ↓↓↓ 把報錯屏蔽了,須要刪除"@"才能看見上面的報錯,
$this->_socket = stream_socket_client( 
            $this->unixSocket ? 'unix://' . $this->unixSocket : 'tcp://' . $this->hostname . ':' . $this->port,
            $errorNumber,      //----這兩個變量沒有提早定義一直報undefined
            $errorDescription, //----這兩個變量沒有提早定義一值報undefined
            $this->connectionTimeout ? $this->connectionTimeout : ini_get("default_socket_timeout")
);

解決方法:編輯php.ini把disable_functions=...中找到stream_socket_server()、stream_socket_client刪除並保存,重啓web組件便可web

相關文章
相關標籤/搜索