Hướng dẫn cài đặt sau đây cũng có thể áp dụng trên các hệ điều phát triển dựa trên Debian như Linux mint, Lubuntu, ...

Chuẩn bị

  • Update thư viện:
sudo apt-get update
  • Cài trình biên dịch (nếu chưa có)
sudo apt-get install build-essential
  • Cài tcl
sudo apt-get install tcl8.5

Cài Redis

Download bản redis mới nhất

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

Giải nén và di chuyển tới thư mục vừa giải nén

tar xzf redis-stable.tar.gz
cd redis-stable

Chạy make command:

make

Chạy kiểm thử

make test

Cuối cùng là cài đặt chính thức

sudo make install

Khi cài đặt xong redis, chúng ta có được một file script cho phép redis chạy nền. Để dùng script này, di chuyển tới thư mục utils

cd utils

Chạy Ubuntu/Debian install script:

sudo ./install_server.sh

Khi script này chạy xong thì redis-server sẽ chạy nền. Có thể dùng các câu lệnh sau để start/stop:

sudo service redis_6379 start
sudo service redis_6379 stop

(Số 6379 thay đổi tùy theo cổng bạn dùng, mặc định là 6379)

Nếu script trên chưa thiết lập redis tự khởi động khi boot máy thì chạy thêm lệnh:

sudo update-rc.d redis_6379 defaults

Cài phpredis

Tải source

wget https://github.com/phpredis/phpredis/archive/develop.zip

Nếu dùng cho PHP7 thì tại thời điểm này có bản đang phát triển:

wget https://github.com/phpredis/phpredis/archive/php7.zip

Giải nén file vừa tải về, di chuyển vào thư mục vừa được giải nén ra và chạy các lệnh sau để cài đặt:

sudo phpize
sudo ./configure
sudo make
sudo make install

Nếu file extension không tự cài đúng thư mục thì copy file redis.so từ trong thư mục modules vào thư mục extension của PHP. Sau đó thêm dòng sau vào file php.ini:

extension = redis.so

Sử dụng phpredis

Ví dụ kết nối tới redis server:

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
try {
    $redis->ping();
} catch(RedisException $e) {
    echo 'Error: ' .  $e->getMessage();
    exit;
}

echo 'Server is running';

Ví dụ sử dụng phpredis đơn giản:

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
try {
    $redis->ping();
} catch(RedisException $e) {
    echo 'Error: ' .  $e->getMessage();
    exit;
}

$redis->set('name', 'Maria');
echo $redis->get('name');

Tài liệu sử dụng Redis: http://redis.io/documentation
Đọc thêm tài liệu chi tiết về cách sử dụng phpredis tại GitHub: https://github.com/phpredis/phpredis