一、安裝Redis和簡單配置
1. 下載Redis安裝包
- 地址:http://redis.io/download , 本文選擇Stable(3.0)版本
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
二、安裝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`
三、配置Yii2的redis擴展(本文使用Yii2 basic 版)
- 官方提供的文檔地址:https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md
1. 安裝Yii2的redis擴展
cd /www/html/basic
php composer.phar require --prefer-dist yiisoft/yii2-redis
2. 配置basic/config/web.php
在components數組中添加如下內容:
'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行開始(因實際而定)
-
變量 errorNumber 、errorDescription ,沒提前定義Yii2 一直報undefined
-
"@"把報錯屏蔽了,一直查不到原因,刪掉"@"才發現stream_socket_client、stream_socket_server()這兩個函數禁用了
更改前
$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")
);
更改後
//也可以不定義這兩個變量,通常項目都會忽略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組件即可