Laravel 作為 PHP 最流行的現代框架,內建優雅的 ORM (Eloquent)、隊列、快取等功能。搭配 MySQL 作為主資料庫、Redis 作為高速快取/隊列儲存,能有效解決高併發下的資料庫瓶頸。本文以 CentOS 6.5、Nginx、PHP 5.4、Laravel 5.0 為例,完整記錄從環境搭建、Composer 安裝、專案初始化、資料庫設定、到 Redis 整合與異步隊列驗證的全流程。
具體安裝步驟請參考官方文件或 yum install nginx php-fpm php-mysql php-mcrypt php-mbstring php-tokenizer php-openssl。
curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer composer -V # 驗證版本號
composer global require "laravel/installer=~1.1" echo 'export PATH="$PATH:~/.composer/vendor/bin"' >> ~/.bash_profile source ~/.bash_profile laravel new myapp # 建立專案目錄 cd myapp
編輯 /etc/nginx/conf.d/default.conf,關鍵 location 區塊:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
重載 Nginx:nginx -s reload。
編輯 config/database.php,設定 MySQL 連線(若用 RDS,填入內網地址)。
建立測試表 tbl_item:
CREATE DATABASE demo;
USE demo;
CREATE TABLE tbl_item (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10,2)
);
INSERT INTO tbl_item (name, price) VALUES ('測試商品', 99.00);
routes.php
Route::get('/item/{id}', 'ItemController@showItem');
ItemController.php
namespace App\Http\Controllers;
use App\Item;
class ItemController extends Controller {
protected $model;
public function __construct() { $this->model = new Item(); }
public function showItem($id) {
$items = $this->model->fetchAll();
return response()->json($items);
}
}
Item.php (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model {
protected $table = 'tbl_item';
protected $fillable = ['name', 'price'];
public function fetchAll() { return $this->all()->toJson(); }
}
瀏覽 https://your-ip/item/1 應回傳 JSON 陣列。
wget https://download.redis.io/releases/redis-3.0.1.tar.gz tar xzf redis-3.0.1.tar.gz && cd redis-3.0.1 make && src/redis-server & # 背景啟動
cd /path/to/myapp # 編輯 composer.json require 區塊加入 "predis/predis": "~1.0" composer update
編輯 config/database.php:
'redis' => [
'cluster' => false,
'default' => ['host' => '127.0.0.1', 'port' => 6379],
],
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Redis;
use App\Item;
class ItemController extends Controller {
protected $model;
public function __construct() { $this->model = new Item(); }
public function showItem($id) {
$redis = Redis::connection('default');
$cacheKey = 'item_list_all';
if ($cached = $redis->get($cacheKey)) {
\Log::info('從 Redis 讀取');
return response($cached)->header('Content-Type', 'application/json');
}
$items = $this->model->fetchAll();
$redis->set($cacheKey, $items); // 可加 EX 設定過期
\Log::info('從 MySQL 讀取並寫入 Redis');
return response($items)->header('Content-Type', 'application/json');
}
}
第二次請求即會命中 Redis,大幅降低 MySQL 負載。
storage、bootstrap/cache 目錄需可寫:chmod -R 775 storage bootstrap/cachecomposer update 記憶體不足,可加 swap 或調整 memory_limit。APP_DEBUG=false、配置 QUEUE_DRIVER=redis、使用 Supervisor 管理隊列進程。完成上述步驟,即擁有一個可水平擴展的 Laravel 應用骨架:MySQL 處理持久化,Redis 加速讀取與隊列異步處理。後續可深入探索 Horizon 監控、Redis Cluster、資料庫讀寫分離等進階架構。