1,469   Laravel Redis

Laravel5提供了使用Redis的配置,通过predis操作Redis。
官网这样说:

Before using Redis with Laravel, you will need to install the predis/predis package (~1.0) via Composer.

predis是一个利用PHP写成的Redis客户端,无需另外安装Redis的扩展,方便使用。

 

这里只讨论Laravel5通过predis使用Redis,具体步骤:

 

1,在项目根目录安装predis

composer require predis/predis

2,在根目录的.env文件配置Redis,或者在config/database.php直接修改;系统已经默认在config/app.php加载Redis的Server Provider了

# .env
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

# config/database.php
'redis' => [

'cluster' => false,

'default' => [
'host' => env('REDIS_HOST', 'localhost'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],

],

3,在控制器中使用Redis

<?php
namespace App\Http\Controllers;
use Redis;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UserController extends Controller
{

public function getProfile()
{

// 获取Redis缓存
$username = Redis::get('username');

return ['username' => $username];
}

public function setProfile(Request $request)
{
$username = $request->input('username');

// 把数据保存到Redis缓存中
Redis::set('username',$username);
return ['status' => 'success'];
}

public function getHome()
{
return view('user.profile');
}
}

 

更多用法查看这里:https://laravel.com/docs/5.2/redis




Leave a Reply

Your email address will not be published. Required fields are marked *